var SideContentFocus = false;
$(document).ready(function () {

    //show cufon text after cufon has been executed
    //$(".bg").css("visibility", "visible");

    $("#hdlCntnr h2").prepend("<span class='icon'></span>");

    //fix navigation for IE 6
    var IE6 = (navigator.appVersion.indexOf("MSIE 6") > 0) ? true : false;
    if (IE6) {
        $("#mNav li").each(function (e) {
            $(this).hover(
              function () {
                  $(this).addClass("hover");
              },
              function () {
                  $(this).removeClass("hover");
              }
            );
        });
    }

    //hook up accordion events
    $(".link-heading a").click(function (e) {
        this.blur();
        e.preventDefault();
        if ($(this).hasClass("on")) {
            _gaq.push(['_trackEvent', 'Expandable Section', this.innerHtml, 'Collapse']);
            $(this).removeClass("on").parent().parent().children(".inner-container").slideUp(300);
        }
        else {
            _gaq.push(['_trackEvent', 'Expandable Section', this.innerHtml, 'Expand']);
            $(this).addClass("on").parent().parent().children(".inner-container").slideDown(300);
        }
    });

    //hook up tab events
    $(".tabs a").click(function (e) {
        e.preventDefault();
        $(this).parent().parent().parent().find(".on").removeClass("on");
        $(this).addClass("on");
        $("#tc-" + $(this).attr("href").replace("#", "")).addClass("on");
    });

    //hook up watermark events
    $(".watermark").focus(function () {
        if (this.value == this.name) {
            this.value = "";
        }
    });
    $(".watermark").blur(function () {
        if (this.value == "") {
            this.value = this.name;
        }
    });

    $("#txtSearch").keypress(function (e) {
        if (e.which == 13) {
            if (this.value != "") {
                window.location.href = "/search-results/?q=" + this.value;
                return false;
            }
        }
    });



    //*** Find a distributor / service tech ***//
    //for enter key
    $("#txtzipcode, #txtzipcode").focus(function () {
        SideContentFocus = true;
    });
    $("#txtzipcode, #txtzipcode").blur(function () {
        SideContentFocus = false;
    });

    $("#txtzipcode").keypress(function (e) {
        if (e.which == 13) {
            if (this.value != "") {
                $("#tc-distributor .searchbtn").trigger("click");
                return false;
            }
        }
    });

    //for enter key
    $("#txtzipcode2").keypress(function (e) {
        if (e.which == 13) {
            if (this.value != "") {
                $("#tc-service-tech .searchbtn").trigger("click");
                return false;
            }
        }
    });

    $("#distrib-loc-us").click(function () {
        $("#txtzipcode").show();
        $(".InternationalCountry").hide();
        $("#tc-distributor-results").html("");
    });
    $("#distrib-loc-international").click(function () {
        $("#txtzipcode").hide();
        $(".InternationalCountry").show();
        $("#tc-distributor-results").html("");
    });
    $("#tc-distributor .searchbtn").click(function (e) {
        e.preventDefault();
        var us = $("#distrib-loc-us")[0].checked;
        var zip = $("#txtzipcode").val();

        var Location = "US";
        if (!us) {
            Location = "International";
        }
        if ((us) && zip != "" && zip != "Please enter your zip code") {
            _gaq.push(['_trackEvent', 'Find A', 'Distributor', zip]);
            $("#tc-distributor-results").load("/sitefiles/ajaxcontent/FindA.aspx?Type=Distributor&Zip=" + zip + "&Location=" + Location, function(data){
              setCookie("FindAResults", data);
            });
            
            setCookie("FindA", "distributor|" + Location + "|" + zip);
        }
        else {
            var Country = $(".InternationalCountry option:selected").val();
            if (Country != "") {
                _gaq.push(['_trackEvent', 'Find A', 'Distributor - Int', escape(Country)]);
                $("#tc-distributor-results").load("/sitefiles/ajaxcontent/FindA.aspx?Type=Distributor&Country=" + escape(Country) + "&Location=" + Location, function(data){
                  setCookie("FindAResults", data);
                });
                
                setCookie("FindA", "distributor|" + Location + "|" + Country);
            }
        }
        


    });
    $("#tc-service-tech .searchbtn").click(function (e) {
        e.preventDefault();
        var us = $("#service-loc-us")[0].checked;
        var zip = $("#txtzipcode2").val().replace(/ /g, "");

        var Location = "US";
        if (!us) {
            Location = "International";
        }
        if ((us || $("#service-loc-international")[0].checked) && zip != "" && zip != "Please enter your zip code") {
            _gaq.push(['_trackEvent', 'Find A', 'Service Tech', zip]);
            $("#tc-service-tech-results").load("/sitefiles/ajaxcontent/FindA.aspx?Type=ServiceTech&Zip=" + zip + "&Location=" + Location, function(data){
              setCookie("FindAResults", data);
            });
            
            setCookie("FindA", "service-tech|" + Location + "|" + zip);
        }
    });

    //*** Ice Wizard ***//
    var IceWizardResults = $("#wizard-results p");
    $(".question").each(function (i) {
        $(this).find("input").click(function () {
            _gaq.push(['_trackEvent', 'Ice Wizard', this.value, 'Selected']);
            var IceWizardCookie = getCookie("IceWizard");
            
            if(IceWizardCookie == null){
              IceWizardCookie = "";
            }
            
            IceWizardResults.hide();

            //for the sake of time...
            if (i == 0) {
                $(".Beverages, .AlcoholicNo, .AlcoholicYes, .BlendedYes, .ChewableNo, .IceBlendedYes").hide();
                IceWizardCookie = "";
            }
            if (i == 1) {
                $(".AlcoholicNo, .AlcoholicYes, .BlendedYes, .ChewableNo, .IceBlendedYes").hide();
                IceWizardCookie = IceWizardCookie.replace("AlcoholicNo|", "").replace("AlcoholicYes|", "").replace("BlendedYes|", "").replace("ChewableNo|", "").replace("ChewableYes|", "").replace("IceBlendedYes|", "").replace("Liquid|", "").replace("Produce|", "").replace("IceBlendedYes|", "").replace("IceBlendedNo|", "").replace("IceProduce|", "").replace("IceLiquid|", "");
            }
            if (i == 2 || i == 3) {
                $(".BlendedYes, .ChewableNo, .IceBlendedYes").hide();
                IceWizardCookie = IceWizardCookie.replace("BlendedYes|", "").replace("BlendedNo|", "").replace("ChewableNo|", "").replace("ChewableYes|", "").replace("IceBlendedYes|", "").replace("IceBlendedNo|", "").replace("Liquid|", "").replace("Produce|", "").replace("IceBlendedYes|", "").replace("IceBlendedNo|", "").replace("IceProduce|", "").replace("IceLiquid|", "");
            }
            if (i == 4) {
                IceWizardCookie = IceWizardCookie.replace("Liquid|", "").replace("Produce|", "");
            }
            if (i == 5) {
                $(".IceBlendedYes").hide();
                IceWizardCookie = IceWizardCookie.replace("IceBlendedYes|", "").replace("IceBlendedNo|", "").replace("IceProduce|", "").replace("IceLiquid|", "");
            }
            if (i == 6) {
                IceWizardCookie = IceWizardCookie.replace("IceProduce|", "").replace("IceLiquid|", "");
            }

            $("." + this.value).fadeIn(300);
            $("." + this.value + " input").attr("checked", "");

            IceWizardCookie += this.value + "|";
            setCookie("IceWizard", IceWizardCookie);
        });
    });
    


    //*** Machine Calc ***//
    $("#business-loc-international").click(function () {
        //convert measurements
        var temp = $("#additional_fields_QSR label");
        $(temp[0]).html("# 207-296 ml drinks served per day");
        $(temp[1]).html("# 355-473 ml drinks served per day");
        $(temp[2]).html("# 532-710 ml drinks served per day");

        temp = $("#additional_fields_Convenience_store label");
        $(temp[0]).html("Peak # of 355 ml drinks/day");
        $(temp[1]).html("Peak # of 592 ml drinks/day");
        $(temp[2]).html("Peak # of 946 ml drinks/day");

        ConvertWidthDropDownToMm($("#available_width"));
        
        _gaq.push(['_trackEvent', 'Machine Calculator', 'International', 'Selected']);
    });
    $("#business-loc-us").click(function () {
        //convert measurements
        var temp = $("#additional_fields_QSR label");
        $(temp[0]).html("# 7-10 oz drinks served per day");
        $(temp[1]).html("# 12-16 oz drinks served per day");
        $(temp[2]).html("# 18-24 oz drinks served per day");

        temp = $("#additional_fields_Convenience_store label");
        $(temp[0]).html("Peak # of 12 oz drinks/day");
        $(temp[1]).html("Peak # of 20 oz drinks/day");
        $(temp[2]).html("Peak # of 32 oz drinks/day");

        ConvertWidthDropDownToIn($("#available_width"));
        
        _gaq.push(['_trackEvent', 'Machine Calculator', 'US', 'Selected']);
    });

    $(".additionalFilter input").keypress(function (e) {
        if ((e.which >= 48 && e.which <= 57) || e.which == 8 || e.which == 0) {
            return true;
        }
        return false;
    });

    var ddlAvailableWidth = $("#available_width");
    var ddlIceType = $("#ice_type");
    var ddlEnterpriseType = $("#enterprise_type");
    $("#ice_type, #enterprise_type, #available_width").change(function () {
        var AvailableWidthVal = ddlAvailableWidth.find("option:selected").val();
        var IceTypeVal = ddlIceType.find("option:selected").val();
        var EnterpriseVal = ddlEnterpriseType.find("option:selected").val();

        $(".additional_fields").hide();
        if (IceTypeVal != "" && EnterpriseVal != "" && AvailableWidthVal != "") {
            DisplayAdditionalFields(EnterpriseVal);
            $("#calc-buttoncontainer").show();
        }
        else {
            $("#calc-buttoncontainer").hide();
        }
    });

    $("#calculatebtn").click(function (e) {
        e.preventDefault();

        var AvailableWidthVal = $("#available_width option:selected").val();
        var IceTypeVal = $("#ice_type option:selected").val();
        var EnterpriseVal = $("#enterprise_type option:selected").val();


        var IsValid = true;
        var ValueStr = "";
        $("#additional_fields_" + EnterpriseVal + " input").each(function () {
            thisObj = $(this);
            if (thisObj.val() == "") {
                IsValid = false;
            }
            ValueStr += thisObj.val() + "|";
        });

        if (IsValid) {

            var BusinessLocation = "US";
            if (!$("#business-loc-us")[0].checked) {
                BusinessLocation = "International";
            }
            var Frequency = "60Hz";
            if (!$("#hertz-req-60")[0].checked) {
                Frequency = "50Hz";
            }

            $("#calc-results").load("/sitefiles/ajaxcontent/MachineCalculator.aspx?BusinessLocation=" + BusinessLocation + "&Frequency=" + Frequency + "&Width=" + AvailableWidthVal + "&IceType=" + IceTypeVal + "&EnterpriseType=" + EnterpriseVal + "&Values=" + ValueStr, function(data){
              setCookie("Calculator", BusinessLocation + "?" + Frequency + "?" + AvailableWidthVal + "?" + IceTypeVal + "?" + EnterpriseVal + "?" + ValueStr);
              setCookie("CalculatorResult", data);
              
              _gaq.push(['_trackEvent', 'Machine Calculator', 'Calculate Data', BusinessLocation + ";" + Frequency + ";" + AvailableWidthVal + ";" + IceTypeVal + ";" + EnterpriseVal + ";" + ValueStr]);
            }).fadeIn(300);

            return false;
        }
    });

    //prepopulate based on cookies
    //Find A...
    var FindA = getCookie("FindA");
    var tempSplit;
    if(FindA != null && FindA != ""){
      $("#accordFindA .link-heading a").removeClass("on");
      $("#accordFindA .inner-container").hide();
      tempSplit = FindA.split("|");

      if(tempSplit[0] == "distributor"){
        if(tempSplit[1] == "US"){
          $("#txtzipcode").val(tempSplit[2]);
         }
         else{
          $("#txtzipcode").hide()
          $(".InternationalCountry").show().val(tempSplit[2]);
          $("#distrib-loc-international").attr("checked", "checked");
         }
      }
      else{
         $("#txtzipcode2").val(tempSplit[2]);
         $("#tc-distributor, #tab-distributor").removeClass("on");
         $("#tc-service-tech, #tab-service-tech").addClass("on");
      }

      $("#tc-" + tempSplit[0] + "-results").html(getCookie("FindAResults"));
    }

    //Ice Wizard
    var IceWizard = getCookie("IceWizard");
    if(IceWizard != null && IceWizard != ""){
      //$("#accordIceWizard .link-heading a").addClass("on");
      //$("#accordIceWizard .inner-container").show();

      tempSplit = IceWizard.split("|");

      for(var i = 0; i < tempSplit.length - 1; i++){
        $("#rb" + tempSplit[i]).attr("checked", "checked");
        $("." + tempSplit[i]).show();
      }
    }
    
    //Calculator
    var Calculator = getCookie("Calculator");
    
    if(Calculator != null && Calculator != ""){
      //$("#accordCalculator .link-heading a").addClass("on");
      //$("#accordCalculator .inner-container").show();
      tempSplit = Calculator.split("?");
      
      if(tempSplit[0] != "US"){
        $("#business-loc-international").attr("checked", "checked");
      }
      if(tempSplit[1] != "60Hz"){
        $("#hertz-req-50").attr("checked", "checked");
      }
      
      $("#available_width").val(tempSplit[2]);
      $("#ice_type").val(tempSplit[3]);
      $("#enterprise_type").val(tempSplit[4]);
      
      $("#calc-buttoncontainer").show();
      var tempFields = $("#additional_fields_" + tempSplit[4]).show();
      
      var Values = tempSplit[5].split("|");
      tempFields.find("input").each(function(i){
        this.value = Values[i];
      });
      
      $("#calc-results").html(getCookie("CalculatorResult")).show();
    }
    
});

function DisplayAdditionalFields(EnterpriseVal) {
    $("#additional_fields_" + EnterpriseVal).fadeIn(300);
}

function ConvertToLb(lb) {
    return parseInt((+lb) * 2.20462262185);
}
function ConvertToKg(lb) {
    return parseInt((+lb) / 2.20462262185);
}
function ConvertToCm(Inches) {
    return Math.round(((+Inches) * 2.54) * 100) / 100;
}
function ConvertToMm(Inches) {
    return Math.round(((+Inches) * 25.4) * 100) / 100;
}
function ConvertToIn(mm) {
    return (+mm) / 25.4;
}

function ConvertWidthDropDownToIn(Obj) {
    Obj.find("option").each(function () {
        var html = this.innerHTML;
        if (html != "--") {
            if (html.indexOf("mm") > -1) {
                var split = html.split("-");
                var temp1 = parseInt(split[0].replace(" mm ", ""));
                if (split.length > 1) {
                    var temp2 = parseInt(split[1].replace(" mm ", ""));
                    this.innerHTML = (Math.round(temp1 / 25.4)) + "\" - " + Math.round(temp2 / 25.4) + "\"";
                }
                else {
                    this.innerHTML = (Math.round(temp1 / 25.4)) + "\"";
                }
            }
        }
    });
}

function ConvertWidthDropDownToCm(Obj) {
    Obj.find("option").each(function () {
        var html = this.innerHTML;
        if (html != "--") {
            if (html.indexOf("\"") > -1) {
                var split = html.split("-");
                var temp1 = parseInt(split[0].replace("\" ", ""));
                if (split.length > 1) {
                    var temp2 = parseInt(split[1].replace("\" ", ""));
                    this.innerHTML = (temp1 * 2.54) + "cm - " + (temp2 * 2.54) + "cm ";
                }
                else {
                    this.innerHTML = (temp1 * 2.54) + "cm";
                }
            }
        }
    });
}

function ConvertWidthDropDownToMm(Obj) {
    Obj.find("option").each(function () {
        var html = this.innerHTML;
        if (html != "--") {
            if (html.indexOf("\"") > -1) {
                var split = html.split("-");
                var temp1 = parseInt(split[0].replace("\" ", ""));
                if (split.length > 1) {
                    var temp2 = parseInt(split[1].replace("\" ", ""));
                    this.innerHTML = (Math.round(temp1 * 25.4)) + " mm - " + (Math.round(temp2 * 25.4)) + " mm ";
                }
                else {
                    this.innerHTML = (Math.round(temp1 * 25.4)) + " mm";
                }
            }
        }
    });
}


function setCookie(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 + "=" + escape(value) + expires + "; path=/";
    
}
/*
function setCookie (name,value, days) {
   value = escape(value);
   var path = "/";
   var date = new Date();
   var theDomain = window.location.host;
   var theCookie = name + "=" + value +
   ((date)    ? "; expires=" + date.toGMTString() : "") +
   ((path)       ? "; path="    + path   : "") +
   ((theDomain)  ? "; domain="  + theDomain : "") +
   ((true)     ? "; secure"            : "");
   document.cookie = theCookie;
}
  */
/*
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}
*/
function getCookie(Name) {
   var search = Name + "="
   if (document.cookie.length > 0) { // if there are any cookies
      var offset = document.cookie.indexOf(search)
      if (offset != -1) { // if cookie exists
         offset += search.length
         // set index of beginning of value
         var end = document.cookie.indexOf(";", offset)
         // set index of end of cookie value
         if (end == -1) end = document.cookie.length
         return unescape(document.cookie.substring(offset, end))
      }
   }
   return "";
}
