﻿//SEARCH BOX AUTO COMPLETE
//========================
function autoComplete() {
    //Only fire auto complete if the length of the textbox query is larger then 2.
    if ($('#txtSearchQuery').val().length > 1) {
        $("#autoCompleteContainer").load("/AjaxAutoComplete/AjaxAutoCompletePage.aspx?query=" +
        $("#txtSearchQuery").val(), function () {
            $("#autoCompleteContainer").slideDown();
        });
    }
}


//Order Replace For First Few Days
//shows a temporary message for the first few days.
function popUpInsteadOfTickets() {
    alert("האתר בבניה בשעות הקרובות, להזמנות 9080*");
}


//Cart Display
//settles the display on whether the cart consists of products or not
function SettleCartDisplay() {
    //Step # 1: Update Total Price
    var newSum = 0;
    var elms = $('#cart_table tr .prod_total span');
    elms.each
   (
       function () {
           newSum += parseInt((($(this).html())));
       }

   );
    $('#lblTotalCartPrice').html(newSum);

    //Settle the display by the total sum :
    if (newSum > 0) {
        $('#noProducts').hide();
        $('#hasProducts').show();
    }
    else {
        $('#noProducts').show();
        $('#hasProducts').hide();
    }


}
//SEARCH BOX MARQUEE EFFECT FUNCTIONS
//===================================
var isMarqueeEffect = true;
//iterate on marquee elements and set the text box content
//to them periodically until the isMarqueeEffect is false.
function getMarqueeElement(iterator) {
    if (isMarqueeEffect) {
        //Ensure that the iterator rotates
        if (iterator > BoxSearchMarqueeCollection.length - 1)
            iterator = 0;
        //Set the textbox to the value
        $('#txtSearchQuery').val(BoxSearchMarqueeCollection[iterator].Value);

        //Call the iterator again
        iterator = iterator + 1;
        setTimeout("getMarqueeElement(" + iterator + ")", 2000);
    }
}

//Cleans the textbox and sets the marquee effect to false,
//if the isMarqueeEffect is true.
function cleanMarqueeEffect()
{
    if (isMarqueeEffect) {
        isMarqueeEffect = false;
        $('#txtSearchQuery').val('');

    }
}


//NEWLETTER REGISTER FORM FUNCTIONS
//======================
//validates the contact form
function validateNewsletterRegisterForm() {
    var isFormValid = true;
    //Step # 1 : Clean the output message label.
    document.getElementById('lblVsRegister').innerHTML = "";

    //Step # 2 : Determine the Fields by reverse order.

    //Validate Email
    if (!(isEmailValid("txtEmail"))) {
        isFormValid = false;
    }

    //Validate Phone
    if (!(isNameValid("txtPhone", 1))) {
        isFormValid = false;
    }

    //Validate Last Name
    if (!(isNameValid("txtFullName", 1))) {
        isFormValid = false;
    }

    //Step # 3 : Determine display of notification and errors.
    if (isFormValid) {
        $('#btnSend')
        .hide();
        $('#ContactLoader')
        .show();
        sleep(500);
        return true;
    }
    else {
        document.getElementById('lblVsRegister').innerHTML +=
         "* אנא מלא את השדות הנחוצים.";
        return false;
    }
}




//CONTACT INPUT ENTER EVENT
//==========================
function GetKeyPressForNewsletterRegisterTextBox(inField, e) {
    var charCode;

    if (e && e.which) {
        charCode = e.which;
    } else if (window.event) {
        e = window.event;
        charCode = e.keyCode;
    }

    if (charCode == 13) {
        document.getElementById("btnSend").click();
    }
}

//BANNER SLIDER
//=============
//Allows changing content between div childs of the container id.
//divId - DOM id of the container
//container - the item to start with. default is 0.
//time Delay to the next iteration
function BannerFader(divId, counter, timeDelayToNextIteration) {
    if ($("#" + divId + " > div").length > 1) { // If there is only one item, then the script is not needed.
        //Step # 1 : Hide all the banner members
        $("#" + divId + " > div").hide();
        //Step # 2 : Show the counter nth child
        $("#" + divId + " > div:nth-child(" + counter + ")").show();
        //Step # 3 : Calculate the next counter
        counter++;
        if (counter > $("#" + divId + " > div").length)
            counter = 1;
        //Step #4 : Call back the Banner Fader
        setTimeout("BannerFader('" + divId + "'," + counter + "," + timeDelayToNextIteration + ")", timeDelayToNextIteration);
    }
    else {
        if ($("#" + divId + " > div").length == 1) {
            $("#" + divId + " > div").show();
        }
    }
}

//BANNER PRINTER
//==============
function getSwf(id, divName, width, height, wmode, src, bgcolor) {
    var divName = document.getElementById(divName);
    var obj = '<OBJECT id="' + id
    + '" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="' +
     width + '" height="' + height + '" style="z-index:0;" ><PARAM NAME="movie" VALUE="' + src + '"><PARAM NAME="wmode" VALUE="' + wmode
     + '"><PARAM NAME="quality" VALUE="high"><param name="bgcolor" value="' + bgcolor + '"><EMBED style="z-index:0;" wmode="' + wmode
     + '" quality="high" src="' + src + '"  width="' + width + '" height="' + height + '" bgcolor="' + bgcolor +
      '" TYPE="application/x-shockwave-flash" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></EMBED></OBJECT>';

    divName.innerHTML = obj;
}

//SEARCH SHOWS FORM
//=================
function validateSearchShowsForm() {
    $("#DdlClub").removeClass("fieldError");
    $("#DdlArtists").removeClass("fieldError");
    if (($("#DdlArtists").val() == "0") && ($("#DdlClub").val() == "0")) 
    {
        $("#DdlClub").addClass("fieldError");
        $("#DdlArtists").addClass("fieldError");
        return false;
    } 
    return true;
}

//FORUM FUNCTIONS
//===============
//validates that the forum search form is ok
function validateForumSearchBox() {
    var isFormValid = true;
    //Validate Writer's Name
    if (!isNameValid("txtSearchInForum", 1))
        isFormValid = false;
    //Step # 3 : Determine display of notification and errors.
    if (isFormValid) {
        $('#btnSearchInForum')
        .hide();
        $('#ajaxLoaderForumSearchBox')
        .show();
        sleep(200);
        return true;
    }
    else {
        return false;
    }
}

//get the enter event for forum search box
function GetKeyPressForForumSearchBox(inField, e) {
    var charCode;

    if (e && e.which) {
        charCode = e.which;
    } else if (window.event) {
        e = window.event;
        charCode = e.keyCode;
    }

    if (charCode == 13) {
        document.getElementById("btnSearchInForum").click();
    }
}

//Activates a message
function activateForumMessage(forumMessageId, linkElementId, securityKeyCode) {
    if (confirm("אתה בטוח שברצונך לאשר הודעה זו")) {
        var xmlhttp;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                //Step X: remove the line from vision.
                $('#' + linkElementId).hide();
            }
        }
        var wcfUrl = "/WebServices/ShoppingService.svc/ActivateForumMessage?forumMessageId=" + forumMessageId + "&securityKeyCode=" + securityKeyCode;
        xmlhttp.open("GET", wcfUrl, true);
        xmlhttp.send();

    } //End confirmation check
}

//Deletes the message
function DeleteForumMessage(forumMessageId, forumBoxElementId , securityKeyCode) {
    if (confirm("אתה בטוח שברצונך למחוק הודעה זו")) {
        var xmlhttp;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        var wcfUrl = "/WebServices/ShoppingService.svc/DeleteForumMessage?forumMessageId=" + forumMessageId + "&securityKeyCode=" + securityKeyCode;
        xmlhttp.open("GET", wcfUrl, true);
        xmlhttp.send();
        //Hide the elements in the forum
        var jqueryId = "#" + forumBoxElementId;
        $(jqueryId).hide();
        jqueryId += "Content";
        $(jqueryId).hide();

    }

}

//validates that the forum is ok
function validateForumAddMessage() {
    var isFormValid = true;
    //Step # 1 : Clean the output message label.
    document.getElementById('lblForumAddMessageOutput').innerHTML = "";
    //Step # 2 : Determine the Fields by reverse order.
    //Validate Writer's Name
    if (!isNameValid("txtForumAddMessageName",1))
        isFormValid = false;

    //Validate Message Title
    if (!isNameValid("txtForumAddMessageHeadline",1))
        isFormValid = false;

    //Step # 3 : Determine display of notification and errors.
    if (isFormValid) {
        $('#btnSubmitAddMessage')
        .hide();
        $('#ajaxLoaderForumAddMessage')
        .show();
        sleep(200);
        return true;
    }
    else {

        document.getElementById('lblForumAddMessageOutput').innerHTML +=
         "* אנא מלא את השדות באדום.";
        return false;
    }
}

//get the enter event for forum add message
function GetKeyPressForForumAddMessage(inField, e) {
    var charCode;

    if (e && e.which) {
        charCode = e.which;
    } else if (window.event) {
        e = window.event;
        charCode = e.keyCode;
    }

    if (charCode == 13) {
        document.getElementById("btnSubmitAddMessage").click();
    }
}

//CART FUNCTIONS
//==============
//mocks an ajax transtition
function mockajaxcart() {
    $('#cart_submit')
        .hide();
    $('#ajaxCartLoader')
        .show();
    sleep(2000);
    return true;
}

//recalculates the totals of the cart
function updateCartTotals() {
    //Step # 1: Update Total Price
    var newSum = 0;
    var elms = $('#cart_table tr .prod_total span');
    elms.each
   (
       function () {
           newSum += parseInt((($(this).html())));
       }

   );
   $('#lblTotalCartPrice').html(newSum);
   //Step # 2 : Get The Delivery Price
   var optionValue = $('#DdlShipmentType').val();
   var deliveryText = $('#DdlShipmentType option[value=' + optionValue + ']').text();
   deliveryText = deliveryText.split(' - ');
   var deliveryPrice = deliveryText[1];
   //Step # 3 : Update Final Total Price
   $('#lblFinalTotalCartPrice').html(newSum + parseInt(deliveryPrice));
}

//update the cart by a specific cart line
function removeFastCartLine(cartLineId, sessionId) {
    if (confirm('אתה בטוח שברצונך להסיר מוצר זה?'))
    {
    //Step 1: Prepare the Ajax Object and send the request.
    var xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            //update the total quantity
            $('#lblCartTotalProductsCount').html(xmlhttp.responseText);
            oldTotal = $('#unitPriceFor' + cartLineId).html();
            //Set the quantity to 0.
            $('#totalPriceFor' + cartLineId).html("0");
            //Hide this line
            $('#tableRowFor' + cartLineId).hide();
            //Update Cart Totals = ]
            updateCartTotals();
            //Call settle display in case we do not have any more products
            SettleCartDisplay();
        }
    }

    var wcfUrl = "WebServices/ShoppingService.svc/RemoveFastCartLine?cartLineId=" + cartLineId + "&sessionId=" + sessionId;
    xmlhttp.open("GET", wcfUrl, true);
    xmlhttp.send();
    }
}

//update the cart by a specific cart line
function updateFastCartLine(cartLineId, sessionId) {
    //Step 0 : Prepare the params
    newQuantity = parseInt($('#QuantityFor'+cartLineId).val());
    //Step 1: Prepare the Ajax Object and send the request.
    var xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            //update the total quantity
            $('#lblCartTotalProductsCount').html(xmlhttp.responseText);
            //Step # 0 : Save the old total
            oldTotal = parseFloat($('#unitPriceFor' + cartLineId).html());
            //Step # 1 : Update the cart line data
            $('#totalPriceFor' + cartLineId).html(
            $('#QuantityFor' + cartLineId).val() *
            $('#unitPriceFor' + cartLineId).html());
            //Step # 2 : Update the total cart price
            updateCartTotals();
            
        }
    }

    var wcfUrl = "WebServices/ShoppingService.svc/UpdateFastCartLine?cartLineId=" + cartLineId + "&newQuantity=" + newQuantity + "&sessionId=" + sessionId;
    xmlhttp.open("GET", wcfUrl, true);
    xmlhttp.send();
}



//COUPON FORM
//===========
function validateCoupon() {
    return isNameValid('ctl00_ContentPlaceHolder1_ctl00_uiCart_txtCouponCode',3);
}

//COUPON INPUT ENTER EVENT
//==========================
function GetKeyPressForCouponTextBox(inField, e) {
    var charCode;

    if (e && e.which) {
        charCode = e.which;
    } else if (window.event) {
        e = window.event;
        charCode = e.keyCode;
    }

    if (charCode == 13) {
        document.getElementById("ctl00_ContentPlaceHolder1_ctl00_uiCart_btnSendCoupon").click();
    }
}

//FORGOT PASSWORD FORM
//====================
function validateForgotPasswordForm() {
    var isFormValid = true;
    //Step # 1 : Clean the output message label.
    document.getElementById('lblOutput').innerHTML = "";
    //Step # 2 : Determine the Fields by reverse order.
    //Validate Email
    if (!(isEmailValid("txtEmail"))) {
        isFormValid = false;
    }

    //Step # 3 : Determine display of notification and errors.
    if (isFormValid) {
        $('#btnLogin')
        .hide();
        $('#ajaxLoginLoaderForgot')
        .show();
        sleep(2000);
        return true;
    }
    else {

        document.getElementById('lblOutput').innerHTML +=
         "* אנא מלא את השדות באדום.";
        return false;
    }
}

//FORGOT INPUT ENTER EVENT
//==========================
function GetKeyPressForForgotTextBox(inField, e) {
    var charCode;

    if (e && e.which) {
        charCode = e.which;
    } else if (window.event) {
        e = window.event;
        charCode = e.keyCode;
    }

    if (charCode == 13) {
        document.getElementById("btnLogin").click();
    }
}


//LOGIN IN ORDER FORM
//===================
//validates the login form
function validateLoginFormInOrderForm() {
    var isFormValid = true;
    //Step # 1 : Clean the output message label.
    document.getElementById('ofvs').innerHTML = "";
    //Step # 2 : Determine the Fields by reverse order.
    //Validate Email
    if (!(isEmailValid("txtLoginEmail"))) {
        isFormValid = false;
    }

    //Validate Password
    if (!(isNameValid("txtLoginPassword", 1))) {
        isFormValid = false;
    }

    //Step # 3 : Determine display of notification and errors.
    if (isFormValid) {
        $('#btnLogin')
        .hide();
        $('#ajaxLoginLoader')
        .show();
        sleep(500);
        return true;
    }
    else {

        document.getElementById('ofvs').innerHTML +=
         "* Please Fill the required Fields.";
        return false;
    }
}

//LOGIN IN ORDER FORM INPUT ENTER EVENT
//=====================================
function GetKeyPressForLoginInOrderFormTextBox(inField, e) {
    var charCode;

    if (e && e.which) {
        charCode = e.which;
    } else if (window.event) {
        e = window.event;
        charCode = e.keyCode;
    }

    if (charCode == 13) {
        document.getElementById("ctl00_ContentPlaceHolder1_ctl00_uiOrderForm_uiLogin_btnLogin").click();
    }
}

//LOGIN
//=====
//validates the login form
function validateLoginForm() {
    var isFormValid = true;
    //Step # 1 : Clean the output message label.
    document.getElementById('ofvs').innerHTML = "";
    //Step # 2 : Determine the Fields by reverse order.
    //Validate Email
    if (!(isEmailValid("txtLoginEmail"))) {
        isFormValid = false;
    }

    //Validate Password
    if (!(isNameValid("txtLoginPassword", 1))) {
        isFormValid = false;
    }

    //Step # 3 : Determine display of notification and errors.
    if (isFormValid) {
        $('#btnLogin')
        .hide();
        $('#ajaxLoginLoader')
        .show();
        sleep(500);
        return true;
    }
    else {
        
        document.getElementById('ofvs').innerHTML +=
         "* אנא מלא את השדות באדום.";
        return false;
    }
}

//LOGIN INPUT ENTER EVENT
//==========================
function GetKeyPressForLoginTextBox(inField, e) {
    var charCode;

    if (e && e.which) {
        charCode = e.which;
    } else if (window.event) {
        e = window.event;
        charCode = e.keyCode;
    }

    if (charCode == 13) {
        document.getElementById("ctl00_ContentPlaceHolder1_ctl00_uiLogin_btnLogin").click();
    }
}


//QUESTION FORM FUNCTIONS
//======================
//validates the question form
function validateQuestionForm() {
    var isFormValid = true;
    //Step # 1 : Clean the output message label.
    document.getElementById('ctl00_ContentPlaceHolder1_ctl00_uiQuestionForm_vsContactForm').innerHTML = "";

    //Step # 2 : Determine the Fields by reverse order.
    //Validate Email
    if (!(isEmailValid("ctl00_ContentPlaceHolder1_ctl00_uiQuestionForm_txtEmail"))) {
        isFormValid = false;
    }

    //Validate Last Name
    if (!(isNameValid("ctl00_ContentPlaceHolder1_ctl00_uiQuestionForm_txtName", 1))) {
        isFormValid = false;
    }

    //Step # 3 : Determine display of notification and errors.
    if (isFormValid) {
        $('#ctl00_ContentPlaceHolder1_ctl00_uiQuestionForm_btnSend')
        .hide();
        $('#QuestionLoader')
        .show();
        sleep(500);
        return true;
    }
    else {
        document.getElementById('ctl00_ContentPlaceHolder1_ctl00_uiQuestionForm_vsContactForm').innerHTML +=
         "* Please Fill the required Fields.";
        return false;
    }
}

//QUESTION INPUT ENTER EVENT
//==========================
function GetKeyPressForQuestionTextBox(inField, e) {
    var charCode;

    if (e && e.which) {
        charCode = e.which;
    } else if (window.event) {
        e = window.event;
        charCode = e.keyCode;
    }

    if (charCode == 13) {
        document.getElementById("ctl00_ContentPlaceHolder1_ctl00_uiQuestionForm_btnSend").click();
    }
}

//CONTACT FORM FUNCTIONS
//======================
//validates the contact form
function validateContactForm() {
    var isFormValid = true ;
    //Step # 1 : Clean the output message label.
    document.getElementById('vsContactForm').innerHTML = "";

    //Step # 2 : Determine the Fields by reverse order.
    //Validate Subject
    if (!(isCheckBoxValid("DdlContactSubject"))){
        isFormValid = false;
    }

    //Validate Email
    if (!(isEmailValid("txtEmail"))) {
        isFormValid = false;
    }

    //Validate Phone
    if (!(isNameValid("txtPhone", 1))) {
        isFormValid = false;
    }

    //Validate Last Name
    if (!(isNameValid("txtName", 1))) {
        isFormValid = false;
    }

    //Step # 3 : Determine display of notification and errors.
    if (isFormValid) {
        $('#btnSend')
        .hide();
        $('#ContactLoader')
        .show();
        sleep(500);
        return true;
    }
    else {
        document.getElementById('vsContactForm').innerHTML +=
         "* Please Fill the required Fields.";
        return false;
    }
}

//validates the ABOUT US > CONTACT US form
function validateAboutUsContactForm() {
    var isFormValid = true;

    //Step # 2 : Determine the Fields by reverse order.
    //Validate Subject
    if (!(isCheckBoxValid("DdlContactSubjectContactUs"))) {
        isFormValid = false;
    }

    //Validate Phone
    if (!(isNameValid("txtPhoneContactUs", 1))) {
        isFormValid = false;
    }

    //Validate Email
    if (!(isEmailValid("txtEmailContactUs"))) {
        isFormValid = false;
    }



    //Validate Last Name
    if (!(isNameValid("txtNameContactUs", 1))) {
        isFormValid = false;
    }

    //Step # 3 : Determine display of notification and errors.
    if (isFormValid) {
        $('#btnSendContactUs')
        .hide();
        $('#ContactLoaderContactUs')
        .show();
        sleep(500);
        return true;
    }
    else {
        return false;
    }
}




//CONTACT INPUT ENTER EVENT
//==========================
function GetKeyPressForContactTextBox(inField, e) {
    var charCode;

    if (e && e.which) {
        charCode = e.which;
    } else if (window.event) {
        e = window.event;
        charCode = e.keyCode;
    }

    if (charCode == 13) {
        document.getElementById("ctl00_ContentPlaceHolder1_ctl00_uiContactForm_btnSend").click();
    }
}

function GetKeyPressForAboutUsContactTextBox(inField, e) {
    var charCode;

    if (e && e.which) {
        charCode = e.which;
    } else if (window.event) {
        e = window.event;
        charCode = e.keyCode;
    }

    if (charCode == 13) {
        document.getElementById("btnSendContactUs").click();
    }
}

//REGISTER FUNCTIONS
//==================
//validate the register form
function validateRegisterForm() {
    
    var isFormValid = true;
    //Step # 1 : Clean the output message label.
    document.getElementById('lblVsRegister').innerHTML = "";

    //Step # 2 : Determine the Fields of the billing information by reverse order.


    //Validate Password
    if (!(isNameValid("txtPassword", 1))) {
        isFormValid = false;
    }

    
    //Validate Email
    if (!(isEmailValid("txtEmail"))) {
        isFormValid = false;
    }

    //Validate Full Name
    if (!(isNameValid("txtFullName", 1))) {
        isFormValid = false;
    }
    
    //Step # 3 : If the Method type is credit then we need to validate

    //Step # 4 : Determine display of notification and errors.
    if (isFormValid) {

        $('#btnSend')
        .hide();
        $('#ajaxLoginLoaderRegister')
        .show();
        sleep(500);
        return true;
    }
    else {
        document.getElementById('lblVsRegister').innerHTML +=
         "* אנא מלאו את השדות האדומים";
        return false;
    }
}

//REGISTER INPUT ENTER EVENT
//==========================
function GetKeyPressForRegisterTextBox(inField, e) {
    var charCode;

    if (e && e.which) {
        charCode = e.which;
    } else if (window.event) {
        e = window.event;
        charCode = e.keyCode;
    }

    if (charCode == 13) {
        document.getElementById("btnSend").click();
    }
}

//update state display
function updateStateDisplay() {
    document.getElementById('ctl00_ContentPlaceHolder1_ctl00_ctl00_pnlStateBox').style.display = 'none';
    document.getElementById('ctl00_ContentPlaceHolder1_ctl00_ctl00_pnlProvinceBox').style.display = 'none';
    if (document.getElementById('ctl00_ContentPlaceHolder1_ctl00_ctl00_DdlCountry').value == 265)
        document.getElementById('ctl00_ContentPlaceHolder1_ctl00_ctl00_pnlStateBox').style.display = 'block';
    if (document.getElementById('ctl00_ContentPlaceHolder1_ctl00_ctl00_DdlCountry').value == 303)
        document.getElementById('ctl00_ContentPlaceHolder1_ctl00_ctl00_pnlProvinceBox').style.display = 'block';
}

//SEARCH BOX FUNCTIONS
//====================
function updateSubCategoryDropDownForSearch() {
    //Clean the select options in the current sub category Drop down
    $('#ctl00_ucSearchBox_DdlSubCategories option').remove();

    //Add the standard "By Sub Category" element
    $('#ctl00_ucSearchBox_DdlSubCategories').append('<option id="0">By Sub Category</option>');

    //Iterate on the mainCategoriesCollection Array
    var i;
    for (i = 0; i < mainCategoriesCollection.length; i++) {
        //If the fatherId suits the selected id,
        if (mainCategoriesCollection[i].FatherId == $('#ctl00_ucSearchBox_DdlCategories').val()) {
            //Add the element to the sub category list
            var syntax = "<option value=" + mainCategoriesCollection[i].Id + ">" + mainCategoriesCollection[i].Name + "</option>";
            $('#ctl00_ucSearchBox_DdlSubCategories').append(syntax);
        }
    }
}


//SEARCH BOX CMS ENTER EVENT
//==========================
function GetKeyPressForCmsSearchTextBox(e) {
    var Key;

    if (window.event)        // IE
    {
        Key = window.event.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        Key = e.which
    }

    if ((Key == 13)&&(validateSearchForm())) {
        validateSearchForm();
    }
    
}

//validate the search form
function validateSearchForm(){
    var result = true;
    if (
        (
        ($('#txtSearchQuery').val() == "חיפוש")
        ||
        ($('#txtSearchQuery').val() == "")
       )
       )
        result = false;
    if (result == true) {
        $('#btnSearch')
        .hide();
        $('#ajaxSearchLoader')
        .show();
        sleep(500);
        window.location = "/searchresults.aspx?q=" + $('#txtSearchQuery').val();
        result = false;
    }
    return result;

}

//PRODUCT VIEW
//============
//updates the display of the PV Slider
function updatePVMediaDisplay(newMediaSrc,newNyroUrl) {
    //Step # 1 : 'Fade Out' the current media
    $('#ctl00_ContentPlaceHolder1_ctl00_imgMediaMain').fadeTo('slow', 0.0, function () {
        //Step # 2 : Change the source of the main media
        $('#ctl00_ContentPlaceHolder1_ctl00_imgMediaMain').attr('src', newMediaSrc);
        //Step # 3 : 'Fade In' the new media display
        $('#ctl00_ContentPlaceHolder1_ctl00_imgMediaMain').fadeTo('slow', 1);
    });

    //Step # 4 : Update the nyroUrl
    $('#ctl00_ContentPlaceHolder1_ctl00_hlkNyro').attr('href', newNyroUrl);
}

//PRODUCT FORM FUNCTION
//=====================
//Validates the product form
function validateProductForm() {
    document.getElementById('ctl00_ContentPlaceHolder1_ctl00_uiProductForm_lblVs').innerHTML =
     "";
    if (isValidInput()) {
        $('#ctl00_ContentPlaceHolder1_ctl00_uiProductForm_btnPurchaseButton')
        .hide();
        $('#productLoader')
        .show();
        sleep(500);
        return true;
    }
    document.getElementById('ctl00_ContentPlaceHolder1_ctl00_uiProductForm_lblVs').innerHTML =
     "Please Fill required fields";
    return false;
}

//Validates the drop downs
function isValidInput() {

    //DROP DOWNS
    var elms =
        $('#ctl00_ContentPlaceHolder1_ctl00_uiProductForm_pnlProductFeatures select');
    var result = true;
    elms.each
   (
       function () {
           var elm = $(this);
           elm.removeClass('fieldError');
           if (elm.val() == 0) {
               result = false;
               elm.addClass('fieldError');
           }
       }
   );

   //TEXT BOXES
   var elms =
        $('#ctl00_ContentPlaceHolder1_ctl00_uiProductForm_pnlProductFeatures input:text');
    elms.each
   (
       function () {
           var elm = $(this);
           elm.removeClass('fieldError');
           if (elm.val() == "") {
               result = false;
               elm.addClass('fieldError');
           }
       }
   );


    return result;
}

//calculate the attached price for an element id.
function getPriceForElement(attachedSelectedId) {
    var attachedPrice = 0;
    var i;
    for (i = 0; i < FeatureValuesCollection.length; i++) {
        //If the required id is in the collection
        if (FeatureValuesCollection[i].Id == attachedSelectedId) {
            //Get the new attached price
            attachedPrice = FeatureValuesCollection[i].Value;
        }
    }
    //return the attached price
    return attachedPrice;
}

//calculate the added price
function CalculateAddedPrice(containerId) {
    //Get all of the elements in the container that are drop downs
    var elms = $('#'+containerId+' select');
    var totalAttachedPrice = 0;
    parseFloat(totalAttachedPrice);

    //Iterate on the elements and attach the added price
    elms.each
    (
        function () {
            var elm = $(this);
            totalAttachedPrice += parseFloat(getPriceForElement(elm.val()));
        }
    );
        return totalAttachedPrice;
    }

//updates the elements for the product price
    function CalculateProductFormTotals() {
        //Get the base price.
        var basePrice = $('#ctl00_ContentPlaceHolder1_ctl00_uiProductForm_lblBasePricePerUnit').html();
        parseFloat(basePrice);

        //get the new added price
        var newPrice = parseFloat(basePrice) +
        parseFloat(CalculateAddedPrice("ctl00_ContentPlaceHolder1_ctl00_uiProductForm_pnlProductFeatures"));

        //update the price label value
        document.getElementById('ctl00_ContentPlaceHolder1_ctl00_uiProductForm_lblPricePerUnit').innerHTML = newPrice;

        //call the update amount function
        updateTotalPriceLabel();
    }


//FORM FUNCTIONS
//==============
//validates textbox field by the char length as a minimum 
//required fields
function isNameValid(id, charLength) {
    var jqueryId = "#" + id;
    if (document.getElementById(id).value.length > charLength) {
        $(jqueryId).removeClass("fieldError");
        return true;
    }
    else {
        $(jqueryId).addClass("fieldError");
        $(jqueryId).focus();
        return false;
    }
}
//Validates the email field
function isEmailValid(id) {
    var jqueryId = "#" + id;
    var filter = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+){1,4}$/;
    if (filter.test(document.getElementById(id).value)) {
        $(jqueryId).removeClass("fieldError");
        return true;
    }
    else {
        $(jqueryId).addClass("fieldError");
        $(jqueryId).focus();
        return false;
    }
}

//validates that the check box has a non default value
function isCheckBoxValid(id) {
    var jqueryId = "#" + id;
    if ($(jqueryId).val() == "0") {
        $(jqueryId).addClass("fieldError");
        $(jqueryId).focus();
        return false;
    }
    else {
        $(jqueryId).removeClass("fieldError");
        return true;
    }
}




//SEO FUNCTIONS
//=============

//REDIRECT THE USER VIA JAVASCRIPT TO KEEP THE STRENGTH OF ANOTHER LINK
function JSLink(url, target) {
    if (target == 0) {
        document.location.href = url;
    }
    else {
        window.open(url);
    }
}

//CART FUNCTIONS
//==========================
//validate the cart form
function validateCartForm() {
    document.getElementById('ctl00_ContentPlaceHolder1_ctl00_uiCart_lblVSCart').innerHTML = "";
    if ($('.cartTotalValue input:radio:checked').length==0) {
        document.getElementById('ctl00_ContentPlaceHolder1_ctl00_uiCart_lblVSCart').innerHTML =
     'Please Select a delivery Method';
        return false;
    }
    $('#ctl00_ContentPlaceHolder1_ctl00_uiCart_btnPurchase')
        .hide();
    $('#ajaxOrderLoader')
        .show();
    sleep(500);
    return true;
}

//Add Fast Cart Line
function addFastCartLine(productId, sessionId) {

    //Step 1: Prepare the Ajax Object and send the request.
    var xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            window.location = "/Cart";
        }
    }
    var wcfUrl = "WebServices/ShoppingService.svc/AddFastCartLine?cmsId=" + productId + "&sessionId=" + sessionId;
    xmlhttp.open("GET", wcfUrl, true);
    xmlhttp.send();
}

//Check that the creditContainer is hidden, if the phoneOrder radio button is checked.
function CheckForPhoneCheck() {
    if (document.getElementById("ctl00_ContentPlaceHolder1_uiOrderForm_radPhone").checked)
        switchToOrderPhone();
}

//Set Credit Elements to default values for the order phone.
function switchToOrderPhone() {
    document.getElementById("ctl00_ContentPlaceHolder1_uiOrderForm_txtCardNumber").value = "4580111133334444";
    document.getElementById("ctl00_ContentPlaceHolder1_uiOrderForm_txtCardCVV").value = "000";
    document.getElementById("ctl00_ContentPlaceHolder1_uiOrderForm_txtCardOwnerName").value = "בוצעה הזמנה טלפונית";
    document.getElementById("ctl00_ContentPlaceHolder1_uiOrderForm_txtCardOwnerId").value = "בוצעה הזמנה טלפונית";
    document.getElementById("ctl00_ContentPlaceHolder1_uiOrderForm_creditContainer").style.display = "none";
    
}


//Set Credit Elements to default values for the order phone.
function switchToOrderCredt() {
    document.getElementById("ctl00_ContentPlaceHolder1_uiOrderForm_txtCardNumber").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_uiOrderForm_txtCardCVV").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_uiOrderForm_txtCardOwnerName").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_uiOrderForm_txtCardOwnerId").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_uiOrderForm_creditContainer").style.display = "block";
}


//Updates the per unit price label.
function CalculateUnitPriceForCart(dropDownId,cartLineId) {
    //Step 1: get the value of the changed element.
    var AddedElementPriceToUnitPrice = PriceDictionary[parseInt(document.getElementById(dropDownId).value)];
    //Step 2: calculate the new currnet unit price.
    document.getElementById("unitPrice_" + cartLineId).innerHTML =
            parseInt(document.getElementById("baseUnitPrice_" + cartLineId).innerHTML) +
            AddedElementPriceToUnitPrice;
    //Step 3: Update the total price.
    updateTotalPriceForCartLine(cartLineId);
}

function updateTotalPriceForCartLine(cartLineId) {
    //Step 1: get the value of the quantity:
    var currentQuantity = parseInt(document.getElementById("quantity_" + cartLineId).value);
    //Step 2: get the value of the price per product:
    var currentPricePerUnit = parseInt(document.getElementById("unitPrice_"+cartLineId).innerHTML);
    //Step 3: Set the total price into the total price label:
    document.getElementById("totalPrice_" + cartLineId).innerHTML = currentQuantity * currentPricePerUnit;
}

//SHARE BAR FUNCTIONS
//===================

//FACEBOOK
function shareFacebook(url) {
    var urlToGo = "http://www.facebook.com/sharer.php?u=" + url;
    window.open(urlToGo, "FacebookShare", "height=436", "width=635", "left=200", "top=100", "location=no", "menubar=no", "resizable=yes",
 "scrollbars=yes", "status=no", "titlebar=no", "toolbar=no");
}

//BOOKMARK
function shareBookMark(title, url) {
    if (window.sidebar) window.sidebar.addPanel(title, url, "");
    else if (window.opera && window.print) {
        var elem = document.createElement('a');
        elem.setAttribute('href', url); elem.setAttribute('title', title); elem.setAttribute('rel', 'sidebar'); elem.click();
    }
    else if (document.all) window.external.AddFavorite(url, title);
}

//REDIRECT TO PRINT FREINDLY PAGE
function sharePrint(url) {
    window.open(url, "",
 "height=800, width=1024, left=200, top=100, location=no, menubar=no, resizable=yes, scrollbars=yes, status=no, titlebar=no, toolbar=YES");
}

//SHARE A FRIEND
function shareWithAFriend(url) {
    window.open(url, "",
"height=400, width=550, left=200, top=100, location=no, menubar=no, resizable=yes, scrollbars=yes, status=no, titlebar=no, toolbar=no");
}

//POP FUNCTIONS
//=============
//SHOWS AN ELEMENT
function ShowPop(id) {
    var popId = "pop" + id;
    document.getElementById(popId).style.display = "block";
}

//HIDES EN ELEMENT
function HidePop(id) {
    var popId = "pop" + id;
    document.getElementById(popId).style.display = "none";
}

//UI Functions
function colorIcon(id, src) {
    document.getElementById(id).src = src;
}


//PRODUCTS FUNCTIONS
//==================
    //Updates the per unit price label.
        function CalculateUnitPrice(dropDownId) {
            //Step 1: get the value of the changed element.
            var AddedElementPriceToUnitPrice = PriceDictionary[parseInt(document.getElementById(dropDownId).value)];
            //Step 2: calculate the new currnet unit price.
            document.getElementById("ctl00_ContentPlaceHolder1_uiProductForm_lblPricePerUnit").innerHTML =
            parseInt(document.getElementById("ctl00_ContentPlaceHolder1_uiProductForm_lblBasePricePerUnit").innerHTML) +
            AddedElementPriceToUnitPrice;
            //Step 3: Update the total price.
            updateTotalPriceLabel();
        }

    //Updates the total price label.
    function updateTotalPriceLabel() {
        //Step 1: get the value of the quantity:
        var currentQuantity = parseInt(document.getElementById("ctl00_ContentPlaceHolder1_ctl00_uiProductForm_DdlQuantity").value);
        //Step 2: get the value of the price per product:
        var currentPricePerUnit = parseInt(document.getElementById("ctl00_ContentPlaceHolder1_ctl00_uiProductForm_lblPricePerUnit").innerHTML);
        //Step 3: Set the total price into the total price label:
        document.getElementById("ctl00_ContentPlaceHolder1_ctl00_uiProductForm_lblTotalPrice").innerHTML = currentQuantity * currentPricePerUnit;
    }

    //Updates the final price label.
    function updateFinalPrice() {
        //Step 1: get the value of the delivery price:
        var deliveryPrice = parseInt(document.getElementById("ctl00_ContentPlaceHolder1_uiCart_DdlDeliveryTypes").value);
        //Step 2: get the value of the price per product:
        var cartTotalPriceBeforeDelivery = parseInt(document.getElementById("ctl00_ContentPlaceHolder1_uiCart_lblCartMiddleSum").innerHTML);
        //Step 3: Set the total price into the total price label:
        document.getElementById("ctl00_ContentPlaceHolder1_uiCart_lblCartFinalPrice").innerHTML = deliveryPrice + cartTotalPriceBeforeDelivery;
    }

    //Adds a cart line through usage of AJAX and WCF
    function AddToCartViaAjax(sessionId) {
        //Step 1: Prepare all the variables to send to the WCF web service.
        var cmsId = document.getElementById("ctl00_ContentPlaceHolder1_uiProductForm_lblProductCmsId").innerHTML;
        var color = document.getElementById("ctl00_ContentPlaceHolder1_uiProductForm_DdlColorChoice").value;
        var size = document.getElementById("ctl00_ContentPlaceHolder1_uiProductForm_DdlSizeChoice").value;
        var type = document.getElementById("ctl00_ContentPlaceHolder1_uiProductForm_DdlTypeChoice").value;
        var quantity = document.getElementById("ctl00_ContentPlaceHolder1_uiProductForm_DdlQuantity").value;
        //Step 2: Prepare the Ajax Object and send the request.
        var xmlhttp;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
       xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("ctl00_ContentPlaceHolder1_uiProductForm_lblAddToCartLineSpan").innerHTML = '<img src=\"Resources/Store/AddToCartDoneButton.png\" alt=\"המוצר בסל\"/>';
                document.getElementById("ctl00_ucPersonalZone_cartLineLink").innerHTML = xmlhttp.responseText;
            }
        }
        var wcfUrl = "WebServices/ShoppingService.svc/AddCartLine?cmsId=" + cmsId + "&color=" + color + "&size=" + size + "&type=" + type + "&quantity=" + quantity + "&sessionId=" + sessionId;
        xmlhttp.open("GET", wcfUrl, true);
        xmlhttp.send();


    }

    //Upates a cart via AJAX and WCF
    function updateCartLine(cartLineId,cartId,isRefresh) {
        
        //Step 1: Prepare all the variables to send to the WCF web service.
        var color = document.getElementById("color_"+cartLineId).value;
        var size = document.getElementById("size_"+cartLineId).value;
        var type = document.getElementById("type_"+cartLineId).value;
        var quantity = document.getElementById("quantity_"+cartLineId).value;
        wcfUrl = "WebServices/ShoppingService.svc/UpdateCartLine?cartLineId=" + cartLineId + "&color=" + color + "&size=" + size + "&type=" + type +
         "&quantity=" + quantity + "&sessionId=" + cartId;

        //Step 2: Prepare the Ajax Object and send the request.
        var xmlhttp;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
       xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("updateSpan_" + cartLineId).src = "/Resources/Cart/updateCartLineDoneButton.png";
                document.getElementById("ctl00_ucPersonalZone_cartLineLink").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", wcfUrl, true);
        xmlhttp.send();
        //if (isRefresh)
           // location.href = "/cms.aspx?nameUrl=Cart";
    }

    //Removes a cart line via AJAX and WCF
    function removeCartLine(cartLineId) {
        if (confirm("Are you sure you wish to remove this product?")) {
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    //Update where we at.
                    location.href = "/Cart";
                }
            }
            var wcfUrl = "WebServices/ShoppingService.svc/RemoveCartLine?cartLineId="+cartLineId;
            xmlhttp.open("GET", wcfUrl, false);
            xmlhttp.send();
            
           
        }//End confirmation check
    }

    //ORDER FORM FUNCTIONS
    //====================
    function validateOrderForm() {
        var isFormValid = true;
        //Step # 1 : Clean the output message label.
        document.getElementById('orderFormVs').innerHTML = "";

        //Step # 2 : Determine the Fields of the billing information by reverse order.


        //Validate Zip
        if (!(isNameValid("txtOrderZip", 1)))
            isFormValid = false;

        //Validate City
        if (!(isNameValid("txtOrderCity", 1))) {
            isFormValid = false;
        }

        //Validate Address
        if (!(isNameValid("txtOrderAddress", 1))) {
            isFormValid = false;
        }

        //Validate Phone
        if (!(isNameValid("txtOrderPhone", 1))) {
            isFormValid = false;
        }

        //Validate Email
        if (!(isEmailValid("txtOrderEmail"))) {
            isFormValid = false;
        }

        //Validate Last Name
        if (!(isNameValid("txtOrderLastName", 1))) {
            isFormValid = false;
        }
        //Validate First Name
        if (!(isNameValid("txtOrderFirstName", 1))) {
            isFormValid = false;
        }

        //Step # 3 : If the Method type is credit then we need to validate
        if ($('#radCreditCard').is(":checked")) {

                //Validate Credit Number
            if (!(isNameValid("txtCardNumber", 7))) {
                document.getElementById('orderFormVs').innerHTML += 
                "* לפחות 7 ספרות במספר הכרטיס</br>";
                    isFormValid = false;
                }
                else {

                    //Validate Credit Number as number
                    if (!(isNumber(document.getElementById('txtCardNumber').value))) {
                        isFormValid = false;
                        document.getElementById('orderFormVs').innerHTML += "* מספר כרטיס האשראי צריך לכלול ספרות בלבד</br>";
                        $('#txtCardNumber').addClass("fieldError");
                        $('#txtCardNumber').focus();
                    }
                    else {
                        $('#txtCardNumber').remove("fieldError");
                    }

                }

                //Validate Credit Type
                if (!(isCheckBoxValid("DdlCreditType"))) {
                    isFormValid = false;
                }

                //Validate Card Owner Name
                if (!(isNameValid("txtCardOwnerName", 1))) {
                    isFormValid = false;
                }

                //Validate Card Owner Id
                if (!(isNameValid("txtCardOwnerId", 1))) {
                    isFormValid = false;
                }

                //Validate CVV
                if (!(isNameValid("txtCreditCvv", 2))) {
                    isFormValid = false;
                }
                else {
                    
                    //Validate Credit Number as number
                    if (
                        !(
                        isNumber(
                        document.getElementById('txtCreditCvv').value
                        )
                        )) {
                        isFormValid = false;
                        document.getElementById('orderFormVs').innerHTML +=
                 "* אנא הכנס ספרות בלבד בשדה 3 ספרות אחרונות.</br>";
                        $('#txtCreditCvv').addClass("fieldError");
                        $('#txtCreditCvv').focus();
                    }
                    else {
                        $('#txtCreditCvv').remove("fieldError");
                    }
                }

                

                //Validate Expiration Date
                var d1 = new Date();
                var d2 = new Date(Number($('#DdlYear').val()),
                 Number($('#DdlMonth').val() - 1), 27, 1, 1, 1);
                //Check month
                if (d1 > d2) {
                    $('#DdlMonth').addClass("fieldError");
                    $('#DdlYear').addClass("fieldError");
                    isFormValid = false;
                    document.getElementById('orderFormVs').innerHTML +=
                 "* כרטיסך לא בתוקף.</br>";
                }
                else {
                    $('#DdlMonth').removeClass("fieldError");
                    $('#DdlYear').removeClass("fieldError");
                }
            }
            //Step # 4 : Determine display of notification and errors.
            if (isFormValid) {
                $('#edit_submit_purchase')
                .hide();
                $('#orderLoading')
                .show();
                sleep(500);
                return true;
            }
            else {
                document.getElementById('orderFormVs').innerHTML +=
         "* אנא מלא את השדות.";
                return false;
            }
        }


        //ORDER INPUT ENTER EVENT
        //==========================
        function GetKeyPressForOrderTextBox(inField, e) {
            var charCode;

            if (e && e.which) {
                charCode = e.which;
            } else if (window.event) {
                e = window.event;
                charCode = e.keyCode;
            }

            if (charCode == 13) {
                document.getElementById("ctl00_ContentPlaceHolder1_ctl00_uiOrderForm_btnOrder").click();
            }
        }





        //update state display
        function updateOrderFormStateDisplay() {
            document.getElementById('ctl00_ContentPlaceHolder1_ctl00_uiOrderForm_pnlStateBox').style.display = 'none';
            document.getElementById('ctl00_ContentPlaceHolder1_ctl00_uiOrderForm_pnlProvinceBox').style.display = 'none';
            if (document.getElementById('ctl00_ContentPlaceHolder1_ctl00_uiOrderForm_DdlCountryId').value == 265)
                document.getElementById('ctl00_ContentPlaceHolder1_ctl00_uiOrderForm_pnlStateBox').style.display = 'block';
            if (document.getElementById('ctl00_ContentPlaceHolder1_ctl00_uiOrderForm_DdlCountryId').value == 303)
                document.getElementById('ctl00_ContentPlaceHolder1_ctl00_uiOrderForm_pnlProvinceBox').style.display = 'block';
        }


        //Shows/Hides the credit box dependent on payment method selected value
        function updateCreditBoxDisplay() {
            if ($('#radCreditCard').is(":checked"))
                $('#creditCardBox').slideDown();
            else
                $('#creditCardBox').slideUp();
        }


    //GENERAL USABILITY
    var numb = '0123456789';
    var lwr = 'abcdefghijklmnopqrstuvwxyz';
    var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

    function isValid(parm, val) {
        if (parm == "") return true;
        for (i = 0; i < parm.length; i++) {
            if (val.indexOf(parm.charAt(i), 0) == -1) return false;
        }
        return true;
    }

    function isNumber(parm) { return isValid(parm, numb); }
    function isLower(parm) { return isValid(parm, lwr); }
    function isUpper(parm) { return isValid(parm, upr); }
    function isAlpha(parm) { return isValid(parm, lwr + upr); }
    function isAlphanum(parm) { return (parm, lwr + upr + numb); }

    /**
    * Delay for a number of milliseconds
    */
    function sleep(delay) {
        var start = new Date().getTime();
        while (new Date().getTime() < start + delay);
    }


    //BRANCHES BIG MAP TAGS

    function showBigMapTag(city) {
        //ensures to hide all branch tags
        $("#mapTooltip_tlv,#mapTooltip_haifa,#mapTooltip_jerusalem,#mapTooltip_bs,#mapTooltip_tveria,#mapTooltip_eilat,#mapTooltip_hasharon,#mapTooltip_zafon").addClass("none");

        var divId = "#mapTooltip_" + city;
        $(divId).removeClass("none");
    }

    //BRANCHES GALLERY

    function branchShowBigImage(imageIndex) {
        var imageId = "#" + imageIndex;
        var imageSrc = $(imageId).attr("src");
        $(".bigImage img").fadeOut(100, function () {
            $(".bigImage img").attr("src", imageSrc);
            $(".bigImage img").fadeIn(100);
        });
        
    }
