includeJS = new Object();
//link which will be navigated on success login
var href = false;
//form which will be submitted on success login
var form = false;
var formType2 = false;
var needRefreshPage = false;

var popupsDiv;
var overlay;


$(document).ready(function(){
    stateElem = $("select[name=address\\[stateId\\]]");
    zipElem = $("input[name=address\\[zip\\]]")
    addrElement = $("select[name=addresses]");
    dropShipAddrElement = $("select[name=dropShipAddresses]");
    
    /*Search-Box placeholder*/
    $(".placeholder").focus(function(){
	if($(this).val() == $(this).data("placeholder")) {
	    $(this).val("");
	}
    });
    $(".placeholder").blur(function(){
	if($(this).val() == "") {
	    $(this).val($(this).data("placeholder"));
	}
    });

    /*Submit form element*/
    $(".submit").change(function(){
	$(this).closest("form").submit();
    });
    $(".submitOnBlur").live("blur", function(){
	$(this).closest("form").submit();
    });
    $("a.submitForm").click(function(){	
	$(this).closest("form").submit();
    });
    $("a.submitFormLive").live("click", function(){
	$(this).closest("form").submit();
    });

    /*Link for input activate*/
    $("a.radioClick").click(function(){
	$("#" + $(this).attr("rel")).trigger("click");
    });
   
    /*2 colums layout - make equal column height*/
    var cLeft = $("div.categoryAdvancedLeft");
    var cRight = $("div.categoryAdvancedRight div.block1RightBottom");
    var hLeft = cLeft.height();
    var hRight = cRight.height();   
    if (hLeft != null && hRight != null) {
	var hMax = hLeft > hRight ? hLeft : hRight;
    //cLeft.css("height", hMax + "px");
    //cRight.css("height", hMax + "px");
    }

   

    $("div.vertical div.seoBoxTitle:first").addClass("first");
    /*Seobox items - make equal column height*/
    hMax = 0;
    $("div.horizontal ul.seoBoxList > li").each(function(){
	if ($(this).height() > hMax) {
	    hMax = $(this).height();
	}
    });
    if (hMax) {
	$("div.horizontal ul.seoBoxList > li").each(function(){
	    $(this).height(hMax);
	});
    }

    /*Change moduleName on product action button click*/
    $("div.productAction > input[type=image]").click(function(){
	$("input[name=data\\[moduleName\\]]").val($(this).attr("name"));
    });


    /*Forms validation*/
    $.validator.setDefaults({
	errorPlacement: function(error, element) {
	    var nextTd = element.parent("td").next("td.errorPlacement");
	    
	    if (nextTd.attr("class")) {
		error.appendTo(nextTd);
	    }
	    else {
		error.insertBefore(element);
	    }
	    
	    
	},
	errorClass: "element",
	errorElement: "li",
	wrapper: "ul class=\"errors\"",
	ignore : ".ignore"
    });    
   
    $("a.login").click(function(e){
	if (checkForAuthAction()) {
	    return true;
	}
	e.preventDefault();
	href = $(this).attr("href");
	showUserAuthForm("userAuth");
    });

    $("input.login").click(function(e){
	if (checkForAuthAction()) {
	    return true;
	}
	e.preventDefault();
	form = $(this).closest("form");
	showUserAuthForm("userAuth");
    });

    $("input.loginType2").click(function(e){
	if (checkForAuthAction()) {
	    return true;
	}
	e.preventDefault();
	formType2 = $(this).closest("form");
	showUserAuthForm("userAuth");	
    });



    // Ajax activity indicator bound to ajax start/stop document events
    $(document).ajaxStart(function(){
	$("#ajaxBusy").show();
    }).ajaxStop(function(){
	$("#ajaxBusy").hide();
    });

    popupsDiv = $("#popups");
    overlay = $("#overlay");
    overlay.click(closePopup);
    $("a.popupClose").live("click", closePopup);
    $("a.popupShow").click(function(){
	var id = $(this).attr("rel");
	showPopup(id);
    });

    /*Login From Handler*/
    $("#forgotPwd").live("click", function(e){
	e.preventDefault();
	showUserAuthForm("userForgotPwd");
    });

    $(".closeForgotPwd").live("click", function(e){
	e.preventDefault();
	closePopup();
	if ($("#userAuth").length > 0) {
	    showPopup("userAuth");
	}
	
    });

    /*Login From Submit*/
    $("body").delegate("#userAuth form", "submit", function(e){
	e.preventDefault();
	$.post(
	    $(this).attr("action"),
	    {
		params:$(this).serialize(),
		rand:Math.random()
	    },
	    function(response) {
		if (response === null) {
		    alert("Internal error");
		    return false;
		}

		if (response.errors !== undefined) {
		    alert(response.errors);
		    return false;
		}

		$('#loginInfo').html(response.data.email);
		$("#anonymousLink").hide();
		updateCartTotal(response.data.cartTotal)

		$(".login").each(function() {
		    $(this).removeClass("login");
		    $(this).unbind("click");
		});


		var headerMenu = $("ul.headerMenu");

		$(".hide", headerMenu).each(function() {
		    $(this).removeClass("hide");
		});

		$(".show", headerMenu).each(function() {
		    $(this).removeClass("show").addClass("hide");
		});
		$("div.btnClose a").click();

		if (document.swf_id_esigns_editor !== undefined) {
		    document.swf_id_esigns_editor.editorLogin(true);
		}

		else if (href && href != "javascript:void(0)") {
		    return window.location.href = href;
		}
		else if (form) {
		    return form.submit();
		}
		else if (formType2) {
		    return formType2.unbind('submit').submit();
		}
		else if (needRefreshPage) {
		    return window.location.reload(true);
		}
		return true;
	    },
	    'json'
	    );


    });

    $("#userForgotPwd form").live("submit", function(e) {
	e.preventDefault();
	$.post(
	    $(this).attr('action'),
	    {
		params:$(this).serialize(),
		rand:Math.random()
	    },
	    function(response) {
		if (response === null) {
		    alert("Internal error");
		    return false;
		}

		if (response.errors !== undefined) {
		    alert(response.errors);
		    return false;
		}
		$("ul.success li").append(response.data).parent().show();
		return true;
	    },
	    'json'
	    );
    });

    $(".search").unbind("ajaxStart ajaxStop");
    /*
    $(".search").bind("keydown", function(e){
	var code = (e.keyCode ? e.keyCode : e.which);
	if (code == 13){
	    $(this).closest("form").submit();
	}
    });
    */
    $(".search").each(function(){
	$(this).autocomplete({
	    minLength: 2,
	    delay : 200,
	    source: function(req, add){
	    $(document).unbind('ajaxStart');
	    var key = req.term;

	    if ($(document.body).data("cache_search_term") == undefined) {
	    $(document.body).data("cache_search_term", new Array());
	    }

	    if ($(document.body).data("cache_search_term")[key] != undefined) {
	    add($(document.body).data("cache_search_term")[key]);
	    }
	    else {
	    getResult(req, add);
	    }
	    }
	    }).data("autocomplete" )._renderItem = function( ul, item ) {
	    return $("<li></li>")
	    .data("item.autocomplete", item)
	    .append("<a> " + item.label +  "</a>")
	    .appendTo(ul);
	};
    });

    $("form.searchForm").submit(function(e){
	var searchInput = $("input[name=q]", this);
	if (searchInput.val() == searchInput.data("placeholder")) {
	    e.preventDefault();
	    return false;
	}
	return true;
    })

    for (var key in includeJS) {
	$.include("/js/" + key + ".js");	
    }        
    
    /*Confirmation before action implementation*/
    $(".confirm").click(function(e){
	var text = $(this).attr("rel") ?  $(this).attr("rel") : "Are you sure?";
	res = confirm(text);
	if (!res) {
	    e.stopPropagation();
	}
	return res;
    });


    if ($("#anonymousLink").length) {
	updateAnonymousDesignsCount($("#anonymousLink").data("designsCount"));
    }

    /*If more then 1 form for validation on page then need this*/
    $("form.needValidate").each( function(){
	$(this).validate();
    });

    /*Snippet roll-over*/
    $("div.snippetAdvancedWrapper").mouseover(function(){
	$("div.snippetAdvancedItem", this).addClass("snippetAdvancedGreen");
	$("div.snippetAdvancedItem", this).removeClass("snippetAdvancedBlue");
	$("div.snippetArrow", this).addClass("snippetArrowGreen");
	$("div.snippetArrow", this).removeClass("snippetArrowBlue");
    })
    $("div.snippetAdvancedWrapper").mouseout(function(){
	$("div.snippetAdvancedItem", this).addClass("snippetAdvancedBlue");
	$("div.snippetAdvancedItem", this).removeClass("snippetAdvancedGreen");
	$("div.snippetArrow", this).addClass("snippetArrowBlue");
	$("div.snippetArrow", this).removeClass("snippetArrowGreen");
    })

    $("ul.homeProducts a.hoverSource").mouseover(function(){
	var parent = $(this).parents("li");
	$(".hoverDest", parent).addClass("hoverOn");
    });
    $("ul.homeProducts a.hoverSource").mouseout(function(){
	var parent = $(this).parents("li");
	$(".hoverDest", parent).removeClass("hoverOn");
    });

    $("a.print").click(function(){
	window.print()
    });

    $("#liveHelp").html("<div id=\"ciVY75\" style=\"z-index:100;position:absolute\"></div><div id=\"scVY75\" style=\"display:inline\"></div><div id=\"sdVY75\" style=\"display:none\"></div><script type=\"text/javascript\">var seVY75=document.createElement(\"script\");seVY75.type=\"text/javascript\";var seVY75s=(location.protocol.indexOf(\"https\")==0?\"https://secure.providesupport.com/image\":\"http://image.providesupport.com\")+\"/js/esigns/safe-textlink.js?ps_h=VY75\u0026ps_t=\"+new Date().getTime()+\"\u0026online-link-html=Live%20Chat\u0026offline-link-html=Live%20Chat\";setTimeout(\"seVY75.src=seVY75s;document.getElementById('sdVY75').appendChild(seVY75)\",1)</script><noscript><div style=\"display:inline\"><a href=\"http://www.providesupport.com?messenger=esigns\">Customer Support</a></div></noscript>");    

    $("a.liveHelp").click(function(){
	$("#liveHelp a").click();
    });

    $("#productSize").live("change", function(e){
	e.preventDefault();
	var productId = $(this).val();
	var params = {
	    productId:productId,
	    discount:1
	};
	var templateSetId = $("input[name=data\\[templateSetId\\]]").val();	
	if (templateSetId) {	
	    params.templateSetId = templateSetId;
	}	
	if ($("table.discountQntDynamic").length) {
	    params.discountDynamic = 1;
	}

	var data = getProductData(params);	
	updateProductData(data);
    })
   
    $("#sortProducts").change(function(){
	$("ul.productList > li").tsort("input[name=sort_" + $(this).val() + "]", {
	    attr:"value"
	});
    })

    var fullDiscountBlock = $("#fullDiscountBlock");
    if (fullDiscountBlock.length) {
	$.ajax({
	    type : "post",
	    url : fullDiscountBlock.data("action"),
	    data: {		
		categoryId:fullDiscountBlock.data('categoryId'),
		groupId:fullDiscountBlock.data('groupId'),
		productId:fullDiscountBlock.data('productId')
	    },
	    success:function(response) {
		data = response;
		if (data == null) {
		    if (response.error) {
			alert(response.error);
			return false;
		    }
		}
		fullDiscountBlock.html(data);
		var linkShowAllDiscounts = $("#showAllDiscounts");
		if (!$("td.hide", fullDiscountBlock).length) {
		    linkShowAllDiscounts.hide();
		}
		else {
		    linkShowAllDiscounts.text(linkShowAllDiscounts.data("txtMore"));
		}
		
	    },
	    dataType: "html"
	});
	$("#showAllDiscounts").live("click", function(){	    
	    var txt = $(this).text() != $(this).data("txtMore") ? $(this).data("txtMore") : $(this).data("txtLess");
	    $(this).text(txt);
	    $("#productDiscounts table td.hide").toggle();
	});
    }

    $("#subscribe").submit(function(e){
	e.preventDefault();
	if (!$(this).valid()) {
	    return;
	}
	var form = $(this);
	var emailInput = $("#subscribeEmail");
	var email = emailInput.val();
	if (email == emailInput.data("placeholder")) {
	    return;
	}

	if (!email) {
	    return;
	}
	$.ajax({
	    type : "post",
	    url : $(this).attr("action"),
	    data: {
		email: email
	    },
	    success:function(response) {
		if (response == null) {
		    return;
		}
		var block = $(document.createElement("div"));		
		var cssClass = "color6";
		if (response.success != null) {
		    block.html(response.success);
		    $(" > input", form).hide();		    
		    $(" > div", form).hide();
		}
		else if (response.errors != null) {
		    block.html(response.errors);
		    cssClass = "color3";
		}
		block.addClass(cssClass);
		form.append(block);		
	    },
	    dataType: "json"
	});
    })

});



/*Center modal windows*/
jQuery.fn.center = function () {
    return this.each(function() {
	var top = ($(window).height() - $(this).outerHeight()) / 2 + 30;
	var left = ($(window).width() - $(this).outerWidth()) / 2;
	$(this).css({
	    position:'absolute',
	    margin:0,
	    top: (top > 0 ? top : 0)+'px',
	    left: (left > 0 ? left : 0)+'px'
	});
    });
}

function showUserAuthForm(id)
{
    if ($("#" + id).attr("id") != null) {
	return showPopup(id);
    }

    var url;
    if (id == "userAuth") {
	url = "/ajax/login-form/";
    }
    else {
	url = "/ajax/forgot-form/";
    }
    $.get(
	url,
	{
	    rand:Math.random()
	},
	function(response) {
	    html = response.html;
	    popupsDiv.append("<div id=\"" + id + "\"> " + response + "</div>");
	    showPopup(id);
	    
	    $("div.btnClose", $("#" + id)).show();
	},
	'html'
	);
    return true;
}

function flashAuth() {
    showUserAuthForm("userAuth");
}

function updateCartTotal(cartTotal) {
    if (cartTotal) {
	var elem = $("#headerCartTotal");
	var regexp = /\$[0-9,]+\.?\d+/gi;
	var text = elem.html();
	text = text.replace(regexp, cartTotal);
	elem.html(text);
    }
}

function getUserEmail() {
    var login = $("#loginInfo").html();
    if (!login) {
	return null
    }
    return login;
}

function checkForAuthAction() {
    return getUserEmail() ? true : false;
}

function getProductData(params)
{	
    var cacheName = "cache_product_info_";
    for (var key in params) {
	cacheName += "_" + key + ":" + params[key];
    }    
    if ($(document.body).data(cacheName)) {
	return $(document.body).data(cacheName);
    }

    $.ajax({
	type : "post",
	url : "/category/product-data/",
	data: params,	
	async:false,
	success:function(response) {
	    
	    if (response == null) {
		return false;
	    }
	    data = response.data;	    
	    if (data == null) {
		if (response.error) {
		    alert(response.error);
		}
		return false;
	    }
	    $(document.body).data(cacheName, data);
	    return data;
	},
	dataType: "json"
    });
    return $(document.body).data(cacheName);
}

function updateProductData(data)
{    
    $("div.productPrice").html(data.price);
    $("#productDiscounts").html(data.discountsHtml);
    $("input[type=hidden][name*=productId]").val(data.productId);
    $("input[type=hidden][name*=productTypeId]").val(data.productTypeId);
    updateLinksForProduct(data);    
}

function updateLinksForProduct(data)
{
    var moduleName = "creation";
    var links = $("#productCustomButtons a[href*=" + moduleName + "]");
    var pattern = "(" + moduleName + "/)([a-z-]+)_([\\w-]+)(.+)";
    var regexp = new RegExp(pattern, "gi");
    links.each(function(){
	var href = $(this).attr("href");
	$(this).attr("href", href.replace(regexp, "$1" + data.categoryName + "_" + data.productName + "$4"))
    })
}


/* Popup functions*/
function showPopup(id) {
    if ($.browser.msie) {
	overlay.css('filter', 'alpha(opacity=75)');
    }
    overlay.fadeIn('fast');
    $("#" + id).fadeIn('fast');
    $("#" + id).center();
    return true;
}

function closePopup() {
    overlay.fadeOut('fast');
    $("> div", popupsDiv).fadeOut('fast');
}

/* Search functions */
function isResult(key)
{
    if ($(document.body).data("cache_search_dictionary") != undefined){
	dictionary = $(document.body).data("cache_search_dictionary");
	for(var i in  dictionary){
	    if (key.indexOf(dictionary[i]) == 0){
		return false;
	    }
	}
    }
    return true;
}
function checkUnique(key, add)
{
    if ($(document.body).data("cache_search_unique") != undefined){
	uniqueItems = $(document.body).data("cache_search_unique");
	for(var i in uniqueItems){
	    if ((key.indexOf(i) == 0) && (uniqueItems[i][0].label.indexOf(key) == 0)){
		add(uniqueItems[i]);
		return false;
	    }
	}
    }
    return true;
}
function needSendPost(key, add)
{
    if (!isResult(key) || !checkUnique(key, add)){
	return false;
    } else {
	return true;
    }
}
function getResult(request, add)
{
    var key = request.term;
    if (!needSendPost(key, add)){
	return false;
    }
    $.getJSON("/search/index/keywords/", request, function(response) {
	var data = response.data;
	if (data) {
	    add(data);

	    $(document.body).data("cache_search_term")[key] = data;
	    if (data.length == 1){
		if ($(document.body).data("cache_search_unique") == undefined) {
		    $(document.body).data("cache_search_unique", new Array());
		}
		$(document.body).data("cache_search_unique")[key] = data;
	    }
	} else {
	    $(".search").each(function(){
		$(this).autocomplete("close");
	    });

	    if ($(document.body).data("cache_search_dictionary") == undefined) {
		$(document.body).data("cache_search_dictionary", new Array());
	    }
	    $(document.body).data("cache_search_dictionary").push(key);
	}
    });
    return false;
}

function updateAnonymousDesignsCount(value)
{    
    var elem = $("#designsCount");
    if (!elem.length) {
	$("#account").addClass("hide");
	var elemListItem = $(document.createElement("li")).attr("id", "anonymousLink");
	var elemLink = $(document.createElement("a")).attr("href", "/designs/").html("My Saved Designs (<span id=\"designsCount\">1</span>)");
	elemLink.appendTo(elemListItem);
	$("#headerCartTotal").after(elemListItem);
	return value;
    }
    $("#designsCount").html(parseInt(value));
    return value;
}

function incAnonymousDesignsCount()
{  
    return updateAnonymousDesignsCount(parseInt($("#designsCount").html()) + 1);
}

function getProductsByCategoryId(categoryId, typeId)
{
    var cacheName = "products_by_category" + categoryId + "_" + typeId;
    if ($(document.body).data(cacheName)) {
	return $(document.body).data(cacheName);
    }

    $.ajax({
	type : "post",
	url : "/category/products-by-category/",
	data: {
	    categoryId:categoryId,
	    typeId:typeId
	},
	async:false,
	success:function(response) {
	    data = response.data;	    
	    $(document.body).data(cacheName, data);	    
	},
	dataType: "json"
    });
    return $(document.body).data(cacheName);
}

function updateSelectByProductsList(productElem, categoryId, typeId, selectedValue)
{
    var data = getProductsByCategoryId(categoryId, typeId);
    updateSelectByList(productElem, data, selectedValue);

}

function getTypesByProductId(productId)
{
    var cacheName = "types_by_product" + productId;
    if ($(document.body).data(cacheName)) {
	return $(document.body).data(cacheName);
    }

    $.ajax({
	type : "post",
	url : "/category/types-by-product/",
	data: {
	    productId:productId
	},
	async:false,
	success:function(response) {
	    data = response.data;
	    $(document.body).data(cacheName, data);	    
	},
	dataType: "json"
    });
    return $(document.body).data(cacheName);
}
