var assortmentpath = '/shop/assortment';
var loginlayerpath = '/shop/loginlayer';
/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
*/
(function ($) {
$.fn.hint = function (blurClass) {
    if (!blurClass) blurClass = 'blur';
    
    return this.each(function () {
        var $input = $(this),
            title = $input.attr('title'),
            $form = $(this.form),
            $win = $(window);

        function remove() {
            if (this.value === title && $input.hasClass(blurClass)) {
                $input.val('').removeClass(blurClass);
								if (this.isPassword) {
									this.type = 'password';
								}
            }
        }

        // 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);
                }
								if (this.type === 'password' && this.value == 'Password') {
									this.isPassword = true;
									this.type = 'text';
								}
            }).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);
/* end remy's plugin */

$('document').ready( function() {
	$('body').addClass("js javascript");
	if( jQuery.browser.msie && (jQuery.browser.version < 7) ) {
		$('body').addClass('ie6');
	}

	activateShopByShape();
	activateBrowseByPrice();
	attachDropDowns();
	rollup();
	activatePersonalizeMenu();
	addPrintPage();
	$('input[type=text]').add('textarea').hint();
	activateChatButton();
	activateAssortmentMessage();
	activateLandingPageCookie();
	initProducts();
});

function rollup() {
	$('.rollup dt').addClass('trigger').each( function(n) {
		$(this).click( function() {
			$(this).next().toggle();
		});
	});
}

function attachDropDowns() {
	function hideSubMenu( elem ) {
		$("#" + elem.id + " ul").hide();
	}
	function showSubMenu( elem ) {
		$("#" + elem.id + " ul").show();
	}
	$('#topnav .main li:has(ul)').each( function(n) {
		var element = this;
		var on = function() {
			$("#" + element.id + " ul").show();
		}
		var off = function() {
			$("#" + element.id + " ul").hide();
		}
		$("#" + this.id + " h3 a").hover( on, off );
		$("#" + this.id + " ul").hover( on, off );
	});
}

function activateShopByShape() {
	$('form.shop_by_shape select').change( function() {
			window.location = browse + this.value;
	});
}

function activateBrowseByPrice() {
	$('form.browse-price select').change( function() {
			window.location = this.value;
	});
}

function activatePersonalizeMenu() {
	var on = function() {
		if ( typeof( timer ) != 'undefined' ) {
			clearTimeout( timer );
		}
		$('.personalize ul').show();
	}
	var off = function () {
		timer = setTimeout( function() { hideSwatches() }, 250 );
	}
	var hold = function() {
		if ( typeof( timer ) != 'undefined' ) {
			clearTimeout( timer );
		}
	}
	var hideSwatches = function() {
		$('.personalize ul').hide();
	}

	var activateSwatches = function() {
		$('.personalize li img').each( function() {
			$(this).click( function() {
				var url = "url(" + this.src + ")";
				$('body').css( "background-image", url );
			});
		});
	}

	$('.personalize a').hover( on, off);
	$('.personalize ul').hover( hold, off);
	activateSwatches();
}

function addPrintPage() {
	$('#js-printpage')
		.html('<a href="#">Print this page</a>')
		.find('a')
		.click(function() { window.print(); });
}

function activateAssortmentMessage() {
	if ( $('#assortmentwrapper').length > 0 ) {
		setAssortmentCookie();
	}
	$('#assortmentwrapper .close a').click( function() {
			$('#assortmentwrapper').remove();
	});
	$('#assortment form input[type=checkbox]').click( function() {
			if (this.checked) {
				setAssortmentCookie();
			}
			else {
				removeAssortmentCookie();
			}
	});
	var options = {
		url : assortmentpath,
		beforeSubmit : function() {
			$('#assortment form input[type=submit]').attr('disabled', true);
		},
		success : function(response) {
			$('#assortment h2').html('Thank You!');
			$('#assortment form').remove();
			$('<p>Your message has been sent to the myShape team.</p>').appendTo('#assortment');
		}
	};
	$('#assortment form').ajaxForm(options);
}

function setAssortmentCookie() {
	myshape.util.createCookie('SkipAssortment','true',365);
}

function removeAssortmentCookie() {
	myshape.util.eraseCookie('SkipAssortment');
}

function activateLandingPageCookie() {
	$('#dont-show input').click( function() {
		if (this.checked) {
			setLandingPageCookie(this.value);
		}
		else {
			removeLandingPageCookie(this.value);
		}
	});
}

function setLandingPageCookie(version) {
		today = new Date();
		expire = new Date();
		diff = 1;
		if (today.getDay() > 0) {
				diff = 8 - today.getDay();
		}
		expire.setTime(today.getTime() + 3600000*24*diff);
		expire.setHours(0);
		expire.setMinutes(0);
		expire.setSeconds(0);
		expire.setMilliseconds(0);
		document.cookie = "SkipLanding=" + version + ";expires=" + expire.toGMTString();
}

function removeLandingPageCookie(version) {
	expire = new Date();
	expire.setTime(today.getTime() - 3600000*24);
	expire.setHours(0);
	expire.setMinutes(0);
	expire.setSeconds(0);
	expire.setMilliseconds(0);
	document.cookie = "SkipLanding=" + version + ";expires=" + expire.toGMTString();
}

function activateChatButton() {
	$('.live-chat').click( function() {
		lpButtonCTTUrl = 'https://server.iad.liveperson.net/hc/91480167/?cmd=file&file=visitorWantsToChat&site=91480167&imageUrl=https://www.myshape.com/images/main/static/liveperson&referrer='+escape(document.location);
		lpButtonCTTUrl = (
			typeof(lpAppendVisitorCookies) != 'undefined' ? lpAppendVisitorCookies(lpButtonCTTUrl) : lpButtonCTTUrl);
			window.open(lpButtonCTTUrl,'chat91480167','width=472,height=320,resizable=yes');
			return false;
	});
}

function initProducts() {
	$('#product_listing .product').each( function() {
		var data = this.title.split('-');
		$(this).find('.buy').click( function(e) {
			
			$.ajax({
			   type: "POST",
			   url: '/shop/cartaddajax',
			   data: "product_id="+data[1]+"&is_in_shop="+data[2]+"&color="+data[3]+"&size="+data[4]+"&wishlist_id="+data[5]+"&wishlist_item_id="+data[6]+"&recipient="+data[7],
			   success: function(msg){
					if (msg.substring(0,6) == 'Error:') {
						newmsg = msg.substring(7);
					} else {
						newmsg = msg;
					}
				  var height = $("#addtocartdialog_"+data[1]).height();
				  var width = $("#addtocartdialog_"+data[1]).width();
				  //calculating offset for displaying popup message
				  leftVal=(e.pageX-(width/2) - 60)+"px";
				  topVal=(e.pageY-(height/2) - 100)+"px";
				  //show the popup message and hide with fading effect
					$("#addtocartdialog_"+data[1]).find("p").html(newmsg);
					
					$("#addtocartdialog_"+data[1]).css({left:leftVal,top:topVal}).show();
					setTimeout('$("#addtocartdialog_'+data[1]+'").fadeOut(1500);', 1500);
					updateShoppingBag();
				}
			});
			
			return false;
		});
		
	});
}

function updateShoppingBag() {
	$.post('/shop/cartcount', null, function(response) { 
		$('#cart-quantity').html(response);
	});
}

function handleEnter (field, event) {
		var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if (keyCode == 13) {
			var i;
			for (i = 0; i < field.form.elements.length; i++)
				if (field == field.form.elements[i])
					break;
			i = (i + 1) % field.form.elements.length;
			field.form.elements[i].focus();
			return false;
		} 
		else
		return true;
	}      
