﻿//ADVERTISING FUNCTIONS
//=====================
function redirectToFlashLink(url) {
    if (confirm("This content is not supported by Apple devices.\nPlease use another device to view it."))
        location.href = url;
}


//FORM FUNCTIONS
//==============
//validates range
function validateCompareNotForInput(id, notComaredValue) {
    var jqueryId = "#" + id;
    if (document.getElementById(id).value != notComaredValue) {
        $(jqueryId).removeClass("fieldError");
        return true;
    }
    else {
        $(jqueryId).addClass("fieldError");
        $(jqueryId).focus();
        return false;
    }
}

//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;
    }
}


//Cleans on focus the default value
function cleanFieldByJSValue(controlId,defaultSyntax) {
    if (document.getElementById(controlId).value == defaultSyntax)
        document.getElementById(controlId).value = "";
}

//Checks if the control is empty and if so, sets it to the default value. 
function setFieldByJSValue(controlId, defaultSyntax) {
    if (document.getElementById(controlId).value == "")
        document.getElementById(controlId).value = defaultSyntax;
}



//CONTACT FORM 
//============
function postContactForm() {
    if (validateContactForm()) {
        $.ajax({
            url: "/ContactFormHandler.ashx",
            dataType: "json",
            type: "POST",
            data: { fullName: $("#txtFullName").val(), email: $("#txtEmail").val(), phone: $("#txtPhone").val(), message: $("#txtMessage").val(), company: $("#txtCompanyName").val() },
            success: function (data) {
                if (data == true) {
                    $("#pnlContactUsFormThanks").show();
                    $("#pnlContactUsForm").hide();
                }
                else {
                    $("#pnlContactUsFormThanks").hide();
                    $("#pnlContactUsForm").show();
                }
            }
        });
    }
}

function validateContactForm() {
    var isFormValid = true; 
    //Validate Full name
    //Step # 1 : Clean the output message label.
    document.getElementById('lblVSContactForm').innerHTML = "";
    //Step # 2 : Determine the Fields of the Contact Form information by reverse order.

    //Validate Full Name
    if (!(validateCompareNotForInput('txtFullName','Full Name')))
    {
        document.getElementById('lblVSContactForm').innerHTML += "* Full Name is required<br/>";
        isFormValid = false;
    }

    //Validate Email
    if (!(validateCompareNotForInput('txtEmail', 'Email'))) {
        document.getElementById('lblVSContactForm').innerHTML += "* Email is required<br/>";
        isFormValid = false;
    }
    else {
        //Validate Email's input
        if (!(isEmailValid('txtEmail'))) {
            document.getElementById('lblVSContactForm').innerHTML += "* Email is invalid<br/>";
            isFormValid = false;
        }
    }

    //Validate Phone
    if (!(validateCompareNotForInput('txtPhone', 'Phone'))) {
        document.getElementById('lblVSContactForm').innerHTML += "* Phone is required<br/>";
        isFormValid = false;
    }
    else {
        //Validate Email's input
        if (isAlpha(document.getElementById('txtPhone').value)) {
            document.getElementById('lblVSContactForm').innerHTML += "* Phone is invalid<br/>";
            isFormValid = false;
        }
    }

    //Validate Comments
    if (!(validateCompareNotForInput('txtMessage','Comments')))
    {
        document.getElementById('lblVSContactForm').innerHTML += "* Comments are required<br/>";
        isFormValid = false;
    }

    return isFormValid;
}


//NEWSLETTER FUNCTIONS
function postNewsLetterForm(e) {
    e.preventDefault();
    if (validateNewsletterForm()) {
        $.ajax({
            url: "/NewsLetterFormHandler.ashx",
            dataType: "json",
            type: "POST",
            data: { NewsletterName: $("#txtNewsletterName").val(), NewsletterEmail: $("#txtNewsletterEmail").val() },
            success: function (data) {
                if (data == true) {
                    $("#pnlNewsletterCanvasThanks").show();
                    $("#pnlNewsletterCanvas").hide();
                }
                else {
                    $("#pnlNewsletterCanvasThanks").hide();
                    $("#pnlNewsletterCanvas").show();
                }
            }
        });
    }
}

function validateNewsletterForm() {
    var isFormValid = true;
    //Validate Full name
    //Step # 1 : Clean the output message label.
    document.getElementById('lblVSNewsletterSummary').innerHTML = "";
    //Step # 2 : Determine the Fields of the Contact Form information by reverse order.

    //Validate Full Name
    if (!(validateCompareNotForInput('txtNewsletterName', 'Full Name'))) {
        document.getElementById('lblVSNewsletterSummary').innerHTML += "* Full Name is required<br/>";
        isFormValid = false;
    }


    //Validate Email
    if (!(validateCompareNotForInput('txtNewsletterEmail', 'Email'))) {
        document.getElementById('lblVSNewsletterSummary').innerHTML += "* Email is required<br/>";
        isFormValid = false;
    }
    else {
        //Validate Email's input
        if (!(isEmailValid('txtNewsletterEmail'))) {
            document.getElementById('lblVSNewsletterSummary').innerHTML += "* Email is invalid<br/>";
            isFormValid = false;
        }
    }

    return isFormValid;
}


//LOGIN FUNCTIONS : SPECIAL
//=========================
//fades the form box into display
function showLoginForm() {
    $('#loginForm').fadeIn('slow');
    $('#loginFormShowLink').fadeOut('slow');
}


//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
//==========================

//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_uiProductForm_DdlQuantity").value);
        //Step 2: get the value of the price per product:
        var currentPricePerUnit = parseInt(document.getElementById("ctl00_ContentPlaceHolder1_uiProductForm_lblPricePerUnit").innerHTML);
        //Step 3: Set the total price into the total price label:
        document.getElementById("ctl00_ContentPlaceHolder1_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, sessionId) {
        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.
                    document.getElementById("cartLine_" + cartLineId).className = "notDisplayed";
                    document.getElementById("ctl00_ucPersonalZone_cartLineLink").innerHTML = xmlhttp.responseText;
                }
            }
            var wcfUrl = "WebServices/ShoppingService.svc/RemoveCartLine?cartLineId="+cartLineId+"&sessionId="+sessionId;
            xmlhttp.open("GET", wcfUrl, true);
            xmlhttp.send();
           
        }//End confirmation check
    }

    //BROWSER AND DEVICE DETECTION
    //================================

    //Notifies the user if the content he is about to see can not be dispalyed by his device.
    function checkIfIphone() {
        if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
            alert("The content you are about to see could contain flash");
        }
    }

    //PROJECT CONTENT SETTLE DISPLAY
    //==================================

    //replaces the content of the main project canvas.
    function replaceContent(id) {
        mainCanvasIE = document.getElementById("mainCanvas");
        hiddenContentIE = document.getElementById("hiddenContent_" + id);
        mainCanvasIE.innerHTML = hiddenContentIE.innerHTML;
    }

    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);} 
