/*
 * 
 *
 */
var cookieSeparator = "";
var wtbGoZipGoState = "zip";
var wtbZipText = "Enter ZIP code";
var wtbCityText = "Enter city";
var wtbOffsetInnerPopup = [0,0];

function setWtbDefaultsFromCookie() {
    var cval = getWtbCookie();
    var breakOuter = false;
    var showWtbOptions = false;
    
    $("#zip2").val(wtbZipText);
    $("#wtbCity").val(wtbCityText);

    if (cval != null && cval.length > 0) {
        var cvalAr = cval.split("|");
        for (var i=0; i<cvalAr.length; i++) {
            var myPairs = cvalAr[i].split("~");
            var myOption = myPairs[0];
            var myVal = myPairs[1];
            var myOpts = [];   
            switch(myOption) {
                case "zip1":
                    $("#zip1").val(myVal);
                    breakOuter=true;
                    break;
                case "Search_Param":
                    $("select[name=Search_Param] option").each(function() {
                        if ($(this).val() == myVal) {
                            $(this).attr("selected", "selected");
                        }
                    });
                    showWtbOptions=true;
                    break;
                case "zip2":
                    $("#zip2").val(myVal);
                    showWtbOptions=true;
                    break;
                case "wtbCity":
                    $("#wtbCity").val(myVal);
                    showWtbOptions=true;
                    break;
                case "wtbState":
                    $("#wtbState option").each(function() {
                        if ($(this).val() == myVal) {
                            $(this).attr("selected", "selected");
                        }
                    });
                    showWtbOptions=true;
                    break;
                default :
                    $("#" + myOption).attr("checked", true);
                    showWtbOptions=true;
                    break;
            }
            if (breakOuter) { break; }
        }
        if (showWtbOptions) {
            moreSearchOptionsClick();
        }
        setWtbCookie(""); // empty cookie
    }
}

function getWtbCookie() {
    var cookiename = "wtb_status";
    var cookiestring=""+document.cookie;
    var index1=cookiestring.indexOf(cookiename);
    if (index1==-1 || cookiename=="") return "";
    var index2=cookiestring.indexOf(';',index1);
    if (index2==-1) index2=cookiestring.length;
    return unescape(cookiestring.substring(index1+cookiename.length+1,index2));
}

function setWtbCookie(value) {
   // alert("set wtb cookie; value = " + ((value==null)? getWtbValsToString() : value));
    var tsValue = (value==null)? getWtbValsToString() : value;
    var today = new Date();
    var expires = new Date(today.getTime() + 2 * 60 * 60 * 1000); // two hours
    document.cookie	= "wtb_status=" + escape(tsValue) + ";"
                    + " expires=" + expires.toGMTString() + ";"
                    + " path=/;";
}

function getWtbValsToString() {
    var result = "";
    $("input[id^=storetype]").each(function() {
        if ($(this)[0].type == 'checkbox' && $(this)[0].checked) {
            result += getCookieSeparator() + $(this).attr("id") + "~on";
        }
    });
    if ($("#zip2").val().length > 0) {
        result += getCookieSeparator() + "zip2~" + $("#zip2").val();
    } else {
        result += getCookieSeparator() + "wtbCity~" + $("#wtbCity").val();
        result += getCookieSeparator() + "wtbState~" + $("#wtbState option:selected").val();
    }
    result += getCookieSeparator() + "Search_Param~" + $("select[name=Search_Param] option:selected").val();
    return result;
}

function getCookieSeparator() {
    if (cookieSeparator=="") { cookieSeparator="|"; return ""; }
    return cookieSeparator;
}

var wheretobuybox = function() {
	var elem = null;
	var pos = {};
	var lbID;

	var openLB = function() {
		if(!($('#'+lbID).length)) {
			elem.after(
				'<div id="'+lbID+'" style="z-index:100;position:absolute;top:'+((1*pos['top'])+300)+'px;left:'+((1*pos['left'])+300)+'px;width:255px;">'+
					'<div  class="lb-detail-top " >&nbsp;</div>'+
					'<div  class="lb-detail-mid " >'+
						'<div class="lb-detail-mid-inner" >'+
							'<div class="lb-detail-mid-inner-inner" >'+
								'<div style="position:absolute;right:8px;top:9px;width:38px;" >'+
								'	<a href="javascript:void(0);" class="lb-closeMe" >Close</a> <a href="javascript:void(0);" class="lb-closeMe" ><img height="7" border="0" width="7" src="/common/images/xClose.gif"/></a>'+
								'</div>'+
								'<div class="lb-detail-load-here"></div>'+
							'</div>'+
						'</div>'+
					'</div>'+
				'</div>'
			);
            $('#'+lbID+' .lb-detail-load-here').load('/wheretobuy/index.ajax.jsp',function(){
                $(this).siblings().find('.lb-closeMe').click(closeLB); 
                initWtb(); 
                $('#'+lbID+' form[name=intSearch]').css("display", "none");
            });
        }

		$('#'+lbID).show();
        return false;
	};

	var closeLB = function() {
		$('#'+lbID).hide();
		return false;
	}
	var closeInnerLB = function() {
		$('.inner-pop').hide().remove();
		return false;
	}


    var popInner = function(arg,url,offset) {
		var innerElem = $(arg);
		var innerPos = innerElem.position();
        var innerParentPos = innerElem.parent().position();
        if (!url) {
            url = "/wheretobuy/" + innerElem.attr("rel") +"-definition.html"
        }
        if (!offset) {
            offset = [0,0];  // top, left
        }

        closeInnerLB();

        innerElem.after(
				'<div class="inner-pop" style="z-index:101;position:absolute;top:'+((1*innerParentPos['top'])+ offset[0]+74)+'px;left:'+((1*innerPos['left']) + offset[1] + 110)+'px;width:255px;">'+
					'<div  class="lb-detail-top " >&nbsp;</div>'+
					'<div  class="lb-detail-mid " style="z-index:100;">'+
						'<div class="lb-detail-mid-inner">'+
                            '<div style="position:absolute;right:8px;top:4px;z-index:103;" >'+
                            '	<a href="javascript:void(0);" class="lb-inner-closeMe" style="color:#990000;">Close</a> <a href="javascript:void(0);" class="lb-inner-closeMe" style="text-decoration-none;"><img height="7" border="0" width="7" style="margin-right:2px;" src="/common/images/xClose.gif"/></a>'+
                            '</div>'+
                            '<div class="lb-detail-mid-inner-inner" >'+
								'<div class="lb-detail-inner-load-here"></div>'+
							'</div>'+
						'</div>'+
					'</div>'+
					'<div class="lb-detail-pointer">&nbsp;</div>'+
				'</div>'
			);
		$('.inner-pop .lb-detail-inner-load-here').load(url,function(){$(this).parents().find('.lb-inner-closeMe').click(closeInnerLB);  });

    }
	var init = function(arg) {
		lbID = 'lb-'+parseInt(100*Math.random(),10);
		elem = $(arg);
		pos = elem.position();

		elem.click(openLB);

	}
	return {
		init : init,
		popInner : popInner,
		closeInnerLB : closeInnerLB,
		closeLB : closeLB
	}
}()


function wtbEmbolden(jObj) {
    jObj.addClass("bold");
    jObj.prev("img:first").attr("src", "/common/images/nav-arrow-on.gif");
}
function wtbEnfeeble(jObj) {
    jObj.removeClass("bold");
    jObj.prev("img:first").attr("src", "/common/images/nav-arrow.gif");
}


function togglePremier() {
    bridgerForm = document.forms["wtbForm2"];
    if(bridgerForm.elements["storetype2_10"] && bridgerForm.elements["storetype2_10"].checked) {
        type1 = document.createElement("INPUT");
        type1.type = "hidden";
        //type1.id = "storetype2_3";
        type1.name = "storetype2_3";
        type1.value = "on";
        bridgerForm.appendChild(type1);
        type2 = document.createElement("INPUT");
        type2.type = "hidden";
        //type2.id = "storetype2_7";
        type2.name = "storetype2_7";
        type2.value = "on";
        bridgerForm.appendChild(type2);
        type3 = document.createElement("INPUT");
        type3.type = "hidden";
        //type3.id = "storetype2_20";
        type3.name = "storetype2_20";
        type3.value = "on";
        bridgerForm.appendChild(type3);
    } else {
        type1 = bridgerForm.elements["storetype2_3"];
        type1.parentNode.removeChild(type1);
        type2 = bridgerForm.elements["storetype2_7"];
        type2.parentNode.removeChild(type2);
        type3 = bridgerForm.elements["storetype2_20"];
        type3.parentNode.removeChild(type3);
    }
}

function togglePrefBuilders() {
    bridgerForm = document.forms["wtbForm2"];
    if(bridgerForm.elements["storetype2_50"].checked) {
        type1 = document.createElement("INPUT");
        type1.type = "hidden";
        type1.id = "storetype2_45";
        type1.name = "storetype2_45";
        type1.value = "on";
        bridgerForm.appendChild(type1);
    } else {
        try {
            type1 = bridgerForm.elements["storetype2_45"];
            type1.parentNode.removeChild(type1);
        } catch (e) {}
    }
}



function moreSearchOptionsClick() {
    /*
    $("#outsideCountry").hide();
    wtbEnfeeble($("#outsideCountryTitle"))

    if ($("#wtbwrapper").is(':visible') && !$("#wtbinnersearch").is(':visible')) {
        // already opened outter div; re-opening more options area and closing int'l area
        $("#wtbinnersearch").show("medium");
        wtbEmbolden($("#wtbMoreSearchOptions"));
        $("#zip1").attr("disabled",true);
        $("#zip2").removeAttr("disabled");
        $("#zip1img").attr("src", "/common/images/btn-go-off.gif")
    }
    else if ($("#wtbwrapper").is(':visible')) {
        $("#wtbwrapper").hide("medium");
        wtbEnfeeble($("#wtbMoreSearchOptions"));
        $("#zip1").removeAttr("disabled");
        $("#zip2").attr("disabled",true);
        $("#zip1img").attr("src", "/common/images/btn-go.gif")
    }
    else {
        $("#wtbinnersearch").show();
        $("#wtbwrapper").show("medium");
        wtbEmbolden($("#wtbMoreSearchOptions"));
        $("#zip1").attr("disabled",true);
        $("#zip2").removeAttr("disabled");
        $("#zip1img").attr("src", "/common/images/btn-go-off.gif")
    }
    */
}

function initWtb() {

    $("#zip1").removeAttr("disabled");
    $("#zip1img").attr("src", "/common/images/btn-go.gif")

    if ($("#wtbMoreOnlineStores")[0]) {
        $("#wtbMoreOnlineStores").unbind();
        $("#wtbMoreOnlineStores").toggle(
            function() { $("#moreOnlineStoresList").show("medium"); wtbEmbolden($(this)); },
            function() { $("#moreOnlineStoresList").hide("medium"); wtbEnfeeble($(this)); }
        );
    }

    $("#wtbForm, #wtbForm2, #wtbMoreSearchOptions, #outsideCountryTitle, #zip2, #zip1, #wtbCity, .whatsthis").unbind();

    $(".whatsthis").click(function() { wheretobuybox.popInner(this, null, wtbOffsetInnerPopup) });

    $("#wtbMoreSearchOptions").click(function() {
        moreSearchOptionsClick();
    });

    /*
    $("#outsideCountryTitle").click(
        function() {
            $("#wtbinnersearch").hide("medium");
            $("#outsideCountry").show("medium");
            wtbEnfeeble($('#wtbMoreSearchOptions'));
            wtbEmbolden($(this));
        }
     );
    */

    $("#zip2, #zip1").focus(function() {
        if ($(this).val() == wtbZipText) {
            $(this).val("");
        }
    });
    $("#zip2, #zip1").blur(function() {
        if ($(this).val() == "") {
            $(this).val(wtbZipText);
        }
    });
    $("#wtbCity").focus(function() {
        if ($(this).val() == wtbCityText) {
            $(this).val("");
        }
    });
    $("#wtbCity").blur(function() {
        if ($(this).val() == "") {
            $(this).val(wtbCityText);
        }
    });

    $("#wtb2img").click(function() {wtbGoZipGoState = "zip"});
    $("#wtb3img").click(function() {wtbGoZipGoState = "state"});

    $("#wtbForm2").submit(function() {
        if (wtbGoZipGoState =="zip") {
            if ($("#zip2").val() == wtbZipText || $("#zip2").val() == "") {
                return false;
            }
            $("#wtbCity").val("");
            $("#wtbState")[0].selectedIndex = 0;
            setWtbCookie(getWtbValsToString());
        } else {
            if ($("#wtbState")[0].selectedIndex == 0) {
                return false;
            }
            if ($("#wtbCity").val() == wtbCityText || $("#wtbCity").val() == "") {
                return false;
            }
            $("#zip2").val("");
            setWtbCookie(getWtbValsToString());
        }
        togglePremier();
        togglePrefBuilders();
    });

    $("#wtbForm").submit(function() {
        if ($("#zip1").val() == wtbZipText || $("#zip1").val() == "") {
            return false;
        }
        if ($("#zip1")[0].disabled) {
            return false;
        }
        setWtbCookie("zip1~" + $("#zip1").val());
    });
    $("form[name=intSearch]").submit(function() {
         setWtbCookie("");
    });

}

$(function() {

    initWtb();

    if ($("a:contains(Where to Buy)")[0]) {
        wheretobuybox.init('a:contains(Where to Buy)');
    }
    
    setWtbDefaultsFromCookie();
    
});
