// -*- mode: Java; -*-

function setProfileColours() {
    if ($('#boxcolour').val()) {
	var bgimg = "url('lib/semitranspng.php?color=" +
	            // escape #
	            $('#boxcolour').val().replace(/#/, '0x');

	if ($('#boxtransparency').val()) {
	    bgimg += '&transparency=' + Math.round(1.27 * $('#boxtransparency').val());
	}

	bgimg += "')";

	$('.sub .box').css('background', bgimg);
	$('.sub h1').css('background', bgimg);
    }

    if ($('#textcolour').val()) {
	$('.box div').css('color', $('#textcolour').val());
    }

    if ($('#highlightcolour').val()) {
	$('.sub h1, .sub h1 a').css('color', $('#highlightcolour').val());
	$('.sub h2, .sub h2 a').css('color', $('#highlightcolour').val());
	$('.blogtitle').css('color', $('#highlightcolour').val());
	$('.box').css('border-top-color', $('#highlightcolour').val());
    }
}

/* change image on mouseover */
function roll_over(img_name, img_src){
   document[img_name].src = img_src;
}

/* check whether terms and conditions have be accepted */
function check_terms(){
	if (document.signinform.waiverights.checked==true){
		document.signinform.submit();
	}
	else{
		alert("You must accept the terms and conditions of this site!");
	}
}

/* Evaluate feedback form */
function evaluate_feedback(){
  var data_correct = true;
  var missing_fields = "";
  if (document.feedbackform.name.value == ""){
    data_correct = false;
    missing_fields = missing_fields + "\nName is empty";
  }
  if (document.feedbackform.email.value == ""){
    data_correct = false;
    missing_fields = missing_fields + "\nEmail is empty";
  }else{
  	if (emailCheck(document.feedbackform.email.value) != true) {
  		data_correct = false;
		  missing_fields = missing_fields + "\nThe email you entered is not valid!";
	  }
	}
	if (document.feedbackform.message.value == ""){
    data_correct = false;
    missing_fields = missing_fields + "\nMessage is empty";
  }
	
	if (data_correct == true){
		document.feedbackform.submit();
		alert('Thank you, your message was sent!');
	}else{
		alert ('Please solve the following problems:'+missing_fields);
	}
	
}
  
/* Evaluate competition form */
function evaluate_competition(){
  var data_correct = true;
  var missing_fields = "";
  if (document.competitionform.yname.value == ""){
    data_correct = false;
    missing_fields = missing_fields + "\nYour name is empty";
  }
  if (document.competitionform.yanswer.value == ""){
      data_correct = false;
      missing_fields = missing_fields + "\nYour answer is empty";
  }  
  if (document.competitionform.yemail.value == ""){
    data_correct = false;
    missing_fields = missing_fields + "\nYour email is empty";
  }else{
  	if (emailCheck(document.competitionform.yemail.value) != true) {
  		data_correct = false;
		  missing_fields = missing_fields + "\nYour email is not valid!";
	  }
	}
  if (document.competitionform.femail.value != ""){
  	if (emailCheck(document.competitionform.femail.value) != true) {
  		data_correct = false;
		  missing_fields = missing_fields + "\nEmail of friend 1 is not valid!";
	  }
	}
	if (document.competitionform.femail2.value != ""){
  	if (emailCheck(document.competitionform.femail2.value) != true) {
  		data_correct = false;
		  missing_fields = missing_fields + "\nEmail of friend 2 is not valid!";
	  }
	}
	if (document.competitionform.femail3.value != ""){
  	if (emailCheck(document.competitionform.femail3.value) != true) {
  		data_correct = false;
		  missing_fields = missing_fields + "\nEmail of friend 3 is not valid!";
	  }
	}
	if (document.competitionform.femail4.value != ""){
  	if (emailCheck(document.competitionform.femail4.value) != true) {
  		data_correct = false;
		  missing_fields = missing_fields + "\nEmail of friend 4 is not valid!";
	  }
	}
	if (data_correct == true){
		document.competitionform.submit();
		alert('Entry registered: Thank you for entering!');
	}else{
		alert ('Please solve the following problems:'+missing_fields);
	}
	
}  

/*	function emailCheck */
/* Changes:  Sandeep V. Tamhankar (stamhankar@hotmail.com) */
/* 1.1.2: Fixed a bug where trailing . in e-mail address was passing
            (the bug is actually in the weak regexp engine of the browser; I
            simplified the regexps to make it work).
   1.1.1: Removed restriction that countries must be preceded by a domain,
            so abc@host.uk is now legal.  However, there's still the 
            restriction that an address must end in a two or three letter
            word.
     1.1: Rewrote most of the function to conform more closely to RFC 822.
     1.0: Original  */

// This script and many more are available free online at
// The JavaScript Source!! http://javascript.internet.com

// Begin
function emailCheck (emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/;
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]";
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")";
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+';
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")";
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat);
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    //alert("The username doesn't seem to be valid.")
    return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        //alert("Destination IP address is invalid!")
		return false;
	    }
    }
    return true;
}

// Domain is symbolic name
var domainArray=domain.match(domainPat);
if (domainArray==null) {
	//alert("The domain name doesn't seem to be valid.")
    return false;
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g");
var domArr=domain.match(atomPat);
var len=domArr.length;
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   //alert("The address must end in a three-letter domain, or two letter country.")
   return false;
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!";
   //alert(errStr)
   return false;
}

// If we've gotten this far, everything's valid!
return true;
}
//  End -->

// Lets you cause the Enter key in an element to trigger the click event
// for some other element.
// This function is dedicated to
// .: Sarah Willcocks and Urs Kemmaman :.
// who requested it.
function enterAction (element, action) {
    $(element).keydown(function (e) {
        if (e.keyCode == 13)
	    $(action).click();
    });
}

function attachtracker () {
    if ($('embed:first').attr('src').search('smiths')) {
        $('embed:first').after('<img src="http://ad.au.doubleclick.net/ad/N5413.2threads/B3411527.13;sz=1x1;ord=[timestamp]" />');
    }
    if ($('embed:last').attr('src').search('smiths')) {
        $('embed:last').after('<img src="http://ad.au.doubleclick.net/ad/N5413.2threads/B3411527.12;sz=1x1;ord=[timestamp]" />');
    }

}

$(document).ready(function() {
    //setTimeout("attachtracker()", 5000);
    $('#footerextension').show();

    // External links open in a new window.
    $("a[href^=http://]:not([href*=2threads.com])").attr('target', '_blank');
		
    // Signup
    //$('#birthdatecalendar').calendar({yearRange:'1920:1990', inline:true, customEvent: function () {alert(this.date)}});
    //$('fieldset.jcalendar').jcalendar();

    // Cover
    $('#covercarousel').jcarousel({scrollAnimation: 'slow',
		                   itemVisible: 1,
		                   itemScroll: 1,
		                   wrap: true,
		                   autoScroll: 5});

    // Homepage
    $('#featuredstylepiccarousel').jcarousel({scrollAnimation: 'slow',
					      itemVisible: 3,
					      itemScroll: 1,
					      wrap: true,
                          wrapPrev: true,
					      autoScroll: 13});

    // Profile
    setProfileColours();

	$('#myvidscarousel').jcarousel({scrollAnimation: 'slow',
                                     itemVisible: 6,
                                     itemScroll: 1,
				     				 wrap: true,
                                     wrapPrev: true,
				     				 autoScroll: 13});

				
	$('#myinspirationscarousel').jcarousel({scrollAnimation: 'slow',
                                  itemVisible: 4,
                                  itemScroll: 1,
	     				 		  wrap: true,
                                  wrapPrev: true,
	     				 		  autoScroll: 13});
	$('#myfanscarousel').jcarousel({scrollAnimation: 'slow',
                                     itemVisible: 4,
                                     itemScroll: 1,
				     				 wrap: true,
                                     wrapPrev: true,
				     				 autoScroll: 13});
	
    $('#myphotoscarousel').jcarousel({scrollAnimation: 'slow',
                                     itemVisible: 6,
                                     itemScroll: 1,
				     				 wrap: true,
                                     wrapPrev: true,
				     				 autoScroll: 13});

 $('#mynewproductscarousel').jcarousel({scrollAnimation: 'slow',
                                     itemVisible: 6,
                                     itemScroll: 1,
				     				 wrap: true,
                                     wrapPrev: true,
				     				 autoScroll: 13});

 $('#myusedproductscarousel').jcarousel({scrollAnimation: 'slow',
                                     itemVisible: 6,
                                     itemScroll: 1,
				     				 wrap: true,
                                     wrapPrev: true,
				     				 autoScroll: 17});

 $('#mynearnewproductscarousel').jcarousel({scrollAnimation: 'slow',
                                     itemVisible: 6,
                                     itemScroll: 1,
				     				 wrap: true,
                                     wrapPrev: true,
				     				 autoScroll: 19});

    $('#mylookscarousel').jcarousel({scrollAnimation: 'slow',
				     itemVisible: 5,
                     itemScroll: 1,
				     wrap: true,
				     wrapPrev: true,
				     autoScroll: 11});
    $('#mystylepicscarousel').jcarousel({scrollAnimation: 'slow',
					 itemVisible: 6,
                     itemScroll: 1,
					 wrap: true,
					 wrapPrev: true,
					 autoScroll: 7});

    $('#myproductsscarousel').jcarousel({scrollAnimation: 'slow',
					 itemVisible: 4,
                     itemScroll: 1,
					 wrap: true,
					 wrapPrev: true,
					 autoScroll: 7});
    $('#mysolditemscarousel').jcarousel({scrollAnimation: 'slow',
					 itemVisible: 4,
                     itemScroll: 1,
					 wrap: true,
					 wrapPrev: true,
					 autoScroll: 7});
    // More uploads
    $('#moreuploads').jcarousel({itemVisible: 2,
				      itemScroll: 1,
				      wrap: true,
	   				  wrapPrev: true});
if ($('#myphotoscarousel ul.shots li').length < 7) {
$('#myphotoscarousel img.jcarousel-next').hide();
$('#myphotoscarousel img.jcarousel-prev').hide();
}
if ($('#mystylepicscarousel ul.shots li').length < 7) {
$('#mystylepicscarousel img.jcarousel-next').hide();
$('#mystylepicscarousel img.jcarousel-prev').hide();
}
if ($('#myvidscarousel ul.shots li').length < 7) {
$('#myvidscarousel img.jcarousel-next').hide();
$('#myvidscarousel img.jcarousel-prev').hide();
}

    // Make music player default only where present.
	// tabs on profile
	$('#mystreams').tabs();
	$('#myphotoshotgoods').tabs();
	$('#myinspirationfans').tabs(); //.triggerTab(2);
	// $('#mysellables').tabs();
	$('#myproducts').tabs();
$('#shop_main_products').tabs();
$('#shop_main_sellers').tabs();

	
	// tabs on homepage
	// photos
		$('#community_photo_threads').tabs().triggerTab(3);

	// videos
		$('#community_threads_videos').tabs().triggerTab(3);
		$('#community_threads_blogs').tabs().triggerTab(3);
	// wishlists/hotgoods
		$('#community_wishlist_threads').tabs();//#.triggerTab(3);

	// members/fashionistas
		$('#community_fashionistas_threads').tabs().triggerTab(3);
		$('#community_products_new_threads').tabs().triggerTab(2);
		$('#community_sellers_threads').tabs().triggerTab(3);

		
	


	    // All pages.
    /*
    // Submenus for the header.
    $('ul.jd_menu').jdMenu();
    //    $(document).bind('click', function () {
    //	$('ul.jd_menu ul:visible').jdMenuHide();
    });
    */

    // Header:Sign in
    // Clear password fields on focus.
    //FIXED: inspired weird "ret[ret.length - 1] has no properties" error
    $("#signup2_button1").click(function () {
    	$('#signin_details').show();
    	$("#signup2_button1").unbind(); 
    	$("#signup2_button1").bind("click", function(){ 
    	 	$('#colours').show();
    	 	$('#signup2_buttondiv1').css("display","none");
    	 	$('#signup2_buttondiv2').show();
    		$("#signup2_button1").unbind(); 
    		$("#signup2_button1").bind("click", function(){ 
    			$('#signup2').submit();
    	 	});
    	});
    });
    
    $(".signform #si_email, #member_si_email").focus(function () {
	if ($(this).val() == 'Enter your email address')
	    $(this).val('');
    });

    /* This field now intentionally left blank.
    $(".signform #si_password, #member_si_password").focus(function () {
	if ($(this).val() == 'password')
	    $(this).val('');
    });
    */
    
    $("#subscribe").focus(function () {
	if ($(this).val() == 'enter your email address here')
	    $(this).val('');
    });
  
    $("#unsubscribe").focus(function () {
	if ($(this).val() == 'your email address')
	    $(this).val('');
    });  

    $("#passwordreset").focus(function () {
	if ($(this).val() == 'Your email address')
	    $(this).val('');
    });

    $("#coversearchkeyword, #searchkeyword").focus(function () {
        if ($(this).val() == 'search')
	    $(this).val('');
    });

    $("#signupbutton").hover(
        function (){$(this).attr("src", "images/sign_up_over.gif");},
        function (){$(this).attr("src", "images/sign_up.gif");}
    );

    $("#signupbuttonbig").hover(
        function (){$(this).attr("src", "images/sign_up_big_over.jpg");},
        function (){$(this).attr("src", "images/sign_up_big.jpg");}
    );

    $("#signup_background").change(function(){
	    $('#signin_aboutme').show('fast');
    });

    // Autoselect searched category option in search panel.
    $("#searchcategory").val($("#selectedcategory").val());

    // Experimental: fade image.
    $('a[href^=image.php]').click(function() {$('.single_image img').fadeOut(1200).fadeIn(3000);});

    enterAction('#coversearchkeyword, #coversearchlocation', 'input.search_box_search');
    // Add case for header search.
    enterAction('#member_si_password', '#member_si');
    enterAction('#searchcategory, #searchkeyword', '#searchkeywordbutton');
    enterAction('#groupsearchkeyword', '#searchkeywordbutton');


    // Truncate overly long links in the footer.
    var twowords = /(\w+\W+\w+\W*$)/;
    var m = twowords.exec($('#second-navigation ul ul li.welcome a').text());
    if (m != null)
        $('#second-navigation ul ul li.welcome a').html(m[1]);

});

