jQuery.fn.hint = function (blurClass) {
  if (!blurClass) { 
    blurClass = 'blur';
  }

  return this.each(function () {
    // get jQuery version of 'this'
    var $input = jQuery(this),

    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = jQuery(this.form),
      $win = jQuery(window);

    function remove() {
      if ($input.val() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }

    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title

      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};


jQuery.create = function() {
    if (arguments.length == 0) return [];
    var args = arguments[0] || {}, elem = null, elements = null;
    var siblings = null;

    // In case someone passes in a null object,
    // assume that they want an empty string.
    if (args == null) args = "";
    if (args.constructor == String) {
        if (arguments.length > 1) {
            var attributes = arguments[1];
                if (attributes.constructor == String) {
                            elem = document.createTextNode(args);
                            elements = [];
                            elements.push(elem);
                            siblings =
        jQuery.create.apply(null, Array.prototype.slice.call(arguments, 1));
                            elements = elements.concat(siblings);
                            return elements;

                    } else {
                            elem = document.createElement(args);

                            // Set element attributes.
                            var attributes = arguments[1];
                            for (var attr in attributes)
                                jQuery(elem).attr(attr, attributes[attr]);

                            // Add children of this element.
                            var children = arguments[2];
                            children = jQuery.create.apply(null, children);
                            jQuery(elem).append(children);

                            // If there are more siblings, render those too.
                            if (arguments.length > 3) {
                                    siblings =
        jQuery.create.apply(null, Array.prototype.slice.call(arguments, 3));
                                    return [elem].concat(siblings);
                            }
                            return elem;
                    }
            } else return document.createTextNode(args);
      } else {
              elements = [];
              elements.push(args);
              siblings =
        jQuery.create.apply(null, (Array.prototype.slice.call(arguments, 1)));
              elements = elements.concat(siblings);
              return elements;
      }
};

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,null);
}

function submitform()
{
	if ($("#ppassword").val() != $("#ppasswordc").val())
		alert('please confirm your password');
	else if ($("#ppassword").val().length < 5)
		alert('your password should be at least 5 characters');
	else if (!isValidEmail($("#email").val()))
		alert('please enter a valid email address');
	else if ($("#duplicate").css('display') != 'none')
		alert('this email address has already been registered');
	else if ($("#profileyob").val() == 0)
		alert('please pick your year of birth');
	else if (($("#profile-page-countries").val() == 0) && !isValidZip($("#profile-page-zip").val())){
		alert('please enter US zipcode or select your country if outside US');
	}
	else
		document.profile.submit();
}

function duplicateEmail() {
	var email = $("#email").val();

	$("#duplicate").css({'color' : 'red', 'display' : 'none'});
	$.post("duplicate.py?rawXML=true", {"email" : email} , function(xml) {
		if($("duplicate", xml).attr("value") == "1"){
			$("#duplicate").css({'color' : 'red', 'display' : 'block'});
		}
	});
};

function processNotMe() {
	var skuid = this.id.substring(1);
	var notme = this.id.substring(0,1);
	var runlogid = $(this).attr("runlogid");
	$.post("email?rawXML=true&ajax=ajax&skuId=" + skuid + "&notMe=" + notme + "&emailRunLogId=" + runlogid, {} , function(xml) {
		if($("Root", xml).attr("success") == "true"){
			if (notme == 2){
				$("#2" + skuid).removeClass().addClass("heartbutton").addClass("hearthighlight").unbind("click", processNotMe);
				$("#1" + skuid).removeClass().addClass("heartclick").addClass("heartbutton").addClass("brokenheartdisabled").bind("click", processNotMe);
			}
			else{
				$("#1" + skuid).removeClass().addClass("heartbutton").addClass("brokenhearthighlight").unbind("click", processNotMe);
				$("#2" + skuid).removeClass().addClass("heartclick").addClass("heartbutton").addClass("heartdisabled").bind("click", processNotMe);
			}
		}
		else{
		}
	});
};

function emailPageInit(){
	$(document).ready(function () {
		$(".heartclick").click(processNotMe);
	});
}

function honHover(){
	$("#hon1,#hon2").hover(
			function(){
				$(this).css({'border' : '10px solid #644264'})
			},
			function(){
				$(this).css({'border' : '10px solid white'})
			}
	);
}

function processFbPic(){
	FB_RequireFeatures(["XFBML"], function(){
		FB.Facebook.init("7441d2d59a622354ab91e5dd01da18c0", "xd_receiver.htm");
		FB.Connect.ifUserConnected(function(){
			uid = FB.Connect.get_loggedInUser();
			FB.Facebook.apiClient.users_getInfo(uid, ['pic_small_with_logo'], function(results){
				var o = $.create('img', 
						{'id':'header-fb-pic', 
					'src':results[0]['pic_small_with_logo']}, []);
				$('#links-main').append($(o));
			});
		},function(){
			alert("you have logged out of facebook. please login again with facebook connect");
			eraseCookie('email');
			eraseCookie('authtoken');
			eraseCookie('user_id');
			eraseCookie('fbuid');
			window.location = '/login';
		});			
	});
}

function logout(){
	eraseCookie('email');
	eraseCookie('authtoken');
	eraseCookie('user_id');
	eraseCookie('fbuid');
	
}

function login() {
	$("#loginloginform").submit();
};

function loginPageInit(){
	$(document).ready(function () {
		
	});
}

function showForgotPasswordModal(){
	$("#loginforgotpassword").modal({
		close:false,
		position: ["30%",],
		opacity: ["50",],
		overlayId:'confirmModalOverlay',
		containerId:'confirmModalContainer'
	});
}

function showForgotPasswordMessage(){
	$("#loginforgotpasswordmb").modal({
		close:false,
		position: ["30%",],
		opacity: ["50",],
		overlayId:'confirmModalOverlay',
		containerId:'confirmModalContainer'
	});	
}

function loginForgotPasswordSubmit(){
	$("#loginforgotpasswordform").submit();
}

function callDialogBox(){
	$("#dialogboxcontent").modal({
		close:false,
		position: ["40%",],
		opacity: ["50",],
		overlayId:'confirmModalOverlay',
		containerId:'confirmModalContainer', 
		onShow: function (dialog) {
		//dialog.data.find('.message').append(message);

		// if the user clicks "yes"
		dialog.data.find('.close').click(function () {
			// close the dialog
			$.modal.close();
		});
	}
	});
}

function submitHON(num)
{
	$("#sel").val(num);
	$("form:UserSelections").submit();
}

function checkHateHeart(){
	$("#hatebrokenheart").show();
	$(".hateleft").each(function(){
		if ($(this).css("display") != "none"){
			$("#hatebrokenheart").hide();
			return false;
		}
	});
}

function hateLeftClick(){
	$("#" + this.id.substring(1)).css({'display':'block'});
	$(this).css({'display':'none'});
	$("#y"+ this.id.substring(1)).remove();
	checkHateHeart();
}

function hateInitLeftPanel(){
	$(".hateleft").each(function(){
		if ($(this).css("display") == "inline"){
			$("#hateclickaddlabel").css({'display':'none'});
			$("#hatebrokenheart").hide();
		}
	});
	
	$(".hateleft").click(hateLeftClick);

	$(".hateright").bind("click", function(e){
		$("#hateclickaddlabel").css({'display':'none'});
		$("#hatebrokenheart").hide();
		var name;
		if (this.id.indexOf("hate_color_dropdown_swatches") != -1)
			name = "hateinput_" + $(this).css("background-color");
		else
			name = "hateinput_" + this.id;
		
		var o = $.create('input',
				{'type':'hidden',
			'name':name, 'id': "y" + this.id}, []);
		$("#hateleftcontentdiv").append($(o));
		$("#x" + this.id).remove().appendTo("#hateleftcontentdiv").click(hateLeftClick);
		$("#x" + this.id).css({'display':'block'});
		$("#"+this.id).css({'display':'none'});
	});
}

function hatePageInit(){
	$(document).ready(function () {
		hateInitLeftPanel();
	});
}

function hateSubmit(){
	$("#hateform").submit();
}

function hateSkip(){
	var o = $.create('input',
			{'type':'hidden',
		'name':'skip', 'value': 'skip'}, []);
	$("#hateform").append($(o)).submit();
}

function categoriesSubmit(){
	$("#catsform").submit();
}

function categoriesSkip(){
	var o = $.create('input',
			{'type':'hidden',
		'name':'skip', 'value': 'skip'}, []);
	$("#catsform").append($(o)).submit();
}

function priceSubmit(){
	$("#priceform").submit();
}

function priceSkip(){
	var o = $.create('input',
			{'type':'hidden',
		'name':'skip', 'value': 'skip'}, []);
	$("#priceform").append($(o)).submit();
}

function showSITMImportDialog(){
	$("#sitmimportdialogcontent").modal({
		close:false,
		position: ["40%",],
		opacity: ["50",],
		overlayId:'confirmModalOverlay',
		containerId:'confirmModalContainer', 
		onShow: function (dialog) {
		//dialog.data.find('.message').append(message);
	}
	});
}

function importSITM(){
	var email = $("#sitmusername").val();
	var password = $("#sitmpassword").val();
	$.post("import?rawXML=true", {"email" : email, 'password' : password} , function(xml) {
		if($("Root", xml).attr("success") == "true"){
			$(xml).find('Size').each(function(){
				$("#CX_" + $(this).attr('value')).each(function(){
					this.checked = true;
				});
			});
		}
		$.modal.close();
	});
}

function honLightBoxSubmit(){
	$("#honform").attr("action", "/size");
	$("#honform").submit();
}

function honLightBoxShow(){
	$("#honlightbox").modal({
		close:false,
		position: ["30%",],
		opacity: ["50",],
		overlayId:'confirmModalOverlay',
		containerId:'confirmModalContainer'
	});
}

function submitSizes(genre){
	var done = false;
	$(".essential").each(function() {
		if (this.checked){
			done=true;
		}	
	});
	if (done){
		$("#sizeform").submit();
	}
	else{
		alert('Please select your size in at least one category');
	}
}

function redirectToContacts(){
	window.location='/contacts?module=message';
}

function allGenresSubmit(){
	$("#allgenresform").submit();
}

function allGenresPrimaryClick(){
	$(".allgenresprimary").css({'background-color' : 'transparent'});
	$(this).css({'background' : 'white'});
	$('.allgenressecondary').css({'display' : 'none'});
	$('.parent-' + $(this).attr('name')).show("slow");
}

function allGenresSecondaryCBEach(){
	var id = "#allgenrespick-" + this.id.substring(11);
	if (this.checked){
		$(id).css({'display':'block'}).addClass("visible");
		var psrc = $(id + " img:first").attr("psrc");
		$(id + " img:first").attr({src : psrc});
		
		psrc = $(id + " img:last").attr("psrc");
		$(id + " img:last").attr({src : psrc});
	}
	else{
		$(id).css({'display':'none'}).removeClass("visible");
	}
	allGenresFixParity();
}

function allGenresSecondaryCBClick(){
	var id = "#allgenrespick-" + this.id.substring(11);
	if (this.checked){
		
		var objDiv = document.getElementById("allgenrespicks");
		objDiv.scrollTop = 0;
		
		$(id).remove().prependTo("#allgenrespicks").addClass("visible");
		$(".allgenresremove").click(allGenresRemoveClick);	
		//$(id).css({'display':'block'});
		var psrc = $(id + " img:first").attr("psrc");
		$(id + " img:first").attr({src : psrc});
		
		psrc = $(id + " img:last").attr("psrc");
		$(id + " img:last").attr({src : psrc});
		$(id).show("slow");
	}
	else{
		//$(id).css({'display':'none'});
		$(id).hide("slow").removeClass("visible");
	}
	allGenresFixParity();
	
	
}

function allGenresRemoveClick(){

	$("#" + this.id.substring(1)).hide("slow").removeClass("visible");
	$("#allgenrecb-" + this.id.substring(15)).each(function() {
		this.checked = false;
	});
	allGenresFixParity();
}

function allGenresFixParity(){
	//var divs = $(".allgenrespicks").each();
	$(".visible").each(function(i){
		if ((i % 2) == 1){
			$(this).css({'background-color': '#f3f1f3'});
			$("#" + this.id + " img:last").css({'z-index': '20'});
		}
		else{
			$(this).css({'background-color': '#ffffff'});
			$("#" + this.id + " img:last").css({'z-index': '1'});
		}
	});
}

function allGenresInit(){
	$(document).ready(function () {
		$(".allgenresprimary").click(allGenresPrimaryClick);	
		$(".allgenressecondarycb").each(allGenresSecondaryCBEach);	
		$(".allgenressecondarycb").click(allGenresSecondaryCBClick);	
		$(".allgenresremove").click(allGenresRemoveClick);	
		
		$('.allgenressecondary').each(function(){
			$(this).cluetip({local:true, cursor: 'pointer',width:'630px',arrows: true, dropShadow: true, showTitle: false, topOffset: '20px', leftOffset: '130px', border: '2px solid #e6e6e6' });
		});
		$(".selected").click().each(allGenresSecondaryCBClick);
		$(".allgenrespicks").each(function(){
			if ($(this).css("display") != "none"){
				var thisid= $("#allgenresprimary" + this.id.substring(this.id.indexOf("-"), this.id.lastIndexOf("-")));
				$(".allgenresprimary").css({'background-color' : 'transparent'});
				thisid.css({'background' : 'white'});
				$('.allgenressecondary').css({'display' : 'none'});
				$('.parent-' + thisid.attr('name')).show("slow");
				return false;
			}
		});
	});
}


function removeWhitespace(string){
     string = (string).replace(/\s*/g,'');
}

function checkForBrandsBG(){
	$(".brandsbgpic").hide();
	$(".brandsbgpic-empty").show();
	
	$(".brandsselected").each(function(){
		if ($(this).css('display') === 'block'){
			$(".brandsbgpic").show();
			$(".brandsbgpic-empty").hide();
			return false;
		}
	});
}

function brandsRemoveClick(){
	$("#x" + this.id.substring(1)).css({'display':'none'});
	$("#cb-" + this.id.substring(1)).each(function() {
		this.checked = false;
	});
	checkForBrandsBG();
}

function brandsCBEach(){
	var id = "#x" + this.id.substring(3);
	if (this.checked){
		$(id).css({'display':'block'});
		$(".brandsbgpic").show();
		$(".brandsbgpic-empty").hide();
	}
	else{
		$(id).css({'display':'none'});
	}
}

function brandsCBClick(){
	var id = "#x" + this.id.substring(3);
	if (this.checked){
		$(id).remove().appendTo("#brandsselecteddiv");
		$("#i" + this.id.substring(3)).click(brandsRemoveClick);
		
		$(id).css({'display':'block'});
		$(".brandsbgpic").show();
		$(".brandsbgpic-empty").hide();
	}
	else{
		$(id).css({'display':'none'});
		checkForBrandsBG();
	}
}

function initBrands(){		
	$(document).ready(function () {
		$(".brandsbgpic").hide();
		$(".brandsbgpic-empty").show();
		
		$(".popular").show();
		$(".brandscb").each(brandsCBEach);	
		$(".brandscb").click(brandsCBClick);	
		$("#brandssearch").bind("keyup", brandsSearch);
		$(".selected input").click().each(brandsCBEach);
		
		$(function(){
			 // find all the input elements with title attributes
			 $("#brandssearch").hint();
			});
		$(".brandsclosebutton").click(brandsRemoveClick);	
	});
}

function brandsSearch(){
	if ($("#brandssearch").val().length > 0){
		$("#brandspopularlabel").hide();
		$(".brandsall label").each(function(){
			if ($(this).text().toLowerCase().indexOf($("#brandssearch").val()) == -1)
				$(this).parent().hide();
			else
				$(this).parent().show();
		});
	}
	else{
		$("#brandspopularlabel").show();
		$(".brandsall").hide();
		$(".popular").show();
	}

}

function brandsSubmit(){
	$("#brandsform").submit();
}

function brandsSkip(){
	var o = $.create('input',
			{'type':'hidden',
		'name':'skip', 'value': 'skip'}, []);
	$("#brandsform").append($(o)).submit();
}

function nextSelectSubmit(){
	$("#nextselectform").submit();
}

function sendSubmit(){
	$("#contactsemailsform").submit();
}

function inviteFormSubmit(){
	$("#inviteform").submit();
}

function genreNameClick(){
	$(".upgenreimage").hide();
	$(".upgenrecollage").hide();
	$(".upgenrename").css({'background-color': 'white'});
	
	$(this).css({'background-color': '#e2dbe2'});
	$("#genreimage" + this.id.substring(9)).show();
	$("#genrecollage" + this.id.substring(9)).show();
}

function initUserProfile(){
	$(document).ready(function () {	
		$(".upgenrename").bind("mouseover", genreNameClick);
		$("#genrename0").click().each(genreNameClick);
	});
}

function submitSweepstakesForm(){
	if (!isValidEmail($("#email").val()))
		alert("Please enter a valid email address");
	else if ($("#email").val() != $("#emailc").val())
		alert("Please confirm your email address");
	else
		$("#sweepform").submit();
		
}

function isValidEmail(str) {

	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1){
	   return false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    return false;
	}

	 if (str.indexOf(at,(lat+1))!=-1){
	    return false;
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    return false;
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
	    return false;
	 }
	
	 if (str.indexOf(" ")!=-1){
	    return false;
	 }

		 return true;			
}

function contactsOptoutSubmit(){
	$("#contactsoptoutform").submit();
}

function contestYes(){
	$("#contestlightbox").modal({
		close:false,
		position: ["30%",],
		opacity: ["50",],
		overlayId:'confirmModalOverlay',
		containerId:'confirmModalContainer'
	});
}

function submitEditProfileForm(){
	if ($("#editppassword").val().length > 0){
		if ($("#editppassword").val().length < 5)
			alert('your password should be at least 5 characters');
		else if ($("#editppassword").val() != $("#editpconfirmpassword").val())
			alert('please confirm your password');
		else
			$("#editprofileform").submit();
	}
	else if ($("#editprofilezip").val().length > 0){
		if ($("#profile-page-countries").val() != "us")
			alert('please leave zipcode empty if outside U.S.');
		else if (!isValidZip($("#editprofilezip").val())){
			alert('the zipcode you entered is not valid');
		}
		else 
			$("#editprofileform").submit();
	}
	else if (($("#editprofilezip").val().length == 0) && ($("#profile-page-countries").val() == "us")){
		alert("please enter a zipcode if in the U.S.");
	}
	else 
		$("#editprofileform").submit();
}

function isValidZip(s)
{
     reZip = new RegExp(/(^\d{5}$)/);
 
     if (!reZip.test(s))
    	 return false;
     else
    	 return true;
}

function unsubscribeSubmit(){
	var o = $.create('input',
			{'type':'hidden',
		'name':'unsubnext', 'value': 'Unsubscribe'}, []);
	$("#unsubform").append($(o)).submit();
}

function unsubBreakSubmit(){
	var o = $.create('input',
			{'type':'hidden',
		'name':'unsubbreak', 'value': 'unsubbreak'}, []);
	$("#unsubbreakform").append($(o)).submit();
}

function unsubChangeSubmit(){
	var o = $.create('input',
			{'type':'hidden',
		'name':'unsubchange', 'value': 'unsubchange'}, []);
	$("#unsubchangeform").append($(o)).submit();	
}

function unpauseSubmit(){
	window.location = '/up?module=unpause';
}

function upPausedLightboxShow(){
	$("#unpauselightbox").modal({
		  overlayCss: {
	    backgroundColor: '#000',
	    overlayId:'confirmModalOverlay',
	    cursor: 'wait',
	    opacity: ["50",]
	  },
	  containerCss: {
		close:false,
		position: ["30%",],
		width: "500px",
		height: "150px",
		backgroundColor: '#fff',
		containerId:'confirmModalContainer'
	}});
}
