$(document).ready(function () {
    if (getQuerystring("id") != "") {
        _divModalProgress = $('#a').crfsModalPanel('divModalProgress');
        _dvCustomerMs = $('#b').crfsModalPanel('dvCustomerMs');

        ////$("#frmCustomerMs").validate();
        $("#btnLoadMs").click(function () {
            showCustomerMs();
        });

        $("#btnCancelMs").click(function () {
            hideCustomerMs();
        });

        $("#btnOkMs").click(function () {
            ////<===
            if (isValidEmail($("#txtEmail").val()) && ($("#txtName").val() != "")) {
                hideCustomerMs();
                loadCustomerMs($("#txtName").val(), $("#txtEmail").val());
            }
            /*
            else
            {
            $("#spanNameMsg").css("display", $("#txtName").val()==""?"block":"none");
            $("#spanEmailMsg").css("display", isValidEmail($("#txtEmail").val())?"none":"block");
            }
            */
        });

        $("#txtName").blur(function () {
            $("#spanNameMsg").css("display", $(this).val() == "" ? "block" : "none");
        });

        $("#txtEmail").blur(function () {
            $("#spanEmailMsg").css("display", isValidEmail($("#txtEmail").val()) ? "none" : "block");
        });

        $("#" + shoppingStep).accordion({
            collapsible: true,
            autoHeight: false

            /*alwaysOpen: false,
            autoHeight: false
            icons: { 'header': 'ui-icon-plus', 'headerSelected': 'ui-icon-minus' }
            active: 'h3.selected',
            header: 'h3.head',
            animated: true,
            showSpeed: 400,
            hideSpeed: 800 */
        });
        $("#" + shoppingStep).bind('accordionchange', function (event, ui) {
            if (_element2scroll != null)
                ScrollToElement(_element2scroll);
        });
        ////$.mask.definitions['d'] = '[9*.99]'; <=== wrong definitions
        $.mask.definitions['s'] = '[SRLsrl]';
        $.mask.definitions['r'] = '[RSrs]';
        $.mask.definitions['n'] = '[12]';
        $.mask.definitions['c'] = '[***]';


        initTextiles();
        initStyles();
        initMeasurements();
        ////$("form").bind('submit', validateShopping);
        ////$("form").bind('submit', function(){alert(); return validateShopping();});
        $("#aspnetForm").bind('submit', function () { return validateShopping(); });
    }
});
var _element2scroll = null;
var _submitted = false;
function validateShopping() {
    if (_submitted == true)
        return;
    ////validate textiles
    if ($("#hdTextiles").val() == "") {
        $("#msgTextiles").css("display", "table-cell");
        _element2scroll = document.getElementById("msgTextiles");
        if ($("#cnt1").css("display") == 'none')
            $("#" + shoppingStep).accordion('activate', 0);
        else
            ScrollToElement(_element2scroll);
        return false;
    }

    ////validate styles
    var ok = true;
    var id;
    $("#divStyles input.styles").each(function (n) {
        id = $(this).attr('id').slice(6);
        if ($(this).val() == "") {
            $("#spanStyleMsg" + id).css("display", "table-cell");
            ok = false;
            return false;
        }
        var svid = "style-value-" + id + "-" + $(this).val();

        if (document.getElementById(svid) != null) {
            svid = "#" + svid;

            if ($(svid).val() == "") {
                $("#spanStyleMsg" + id).css("display", "table-cell");
                ok = false;
                return false;
            }
        }
    });
    if (ok == false) {
        _element2scroll = document.getElementById("spanStyleMsg" + id);
        if ($("#cnt2").css("display") == 'none')
            $("#" + shoppingStep).accordion('activate', 1);
        else
            ScrollToElement(_element2scroll);
        return false;
    }

    ////var rdMeasurement = $("#dvMeasurements table:first").find("input:radio:checked");
    var rdMeasurement = $("#dvMeasurements input:radio:checked");
    if (rdMeasurement.val() == undefined) {
        _element2scroll = document.getElementById("spanMeasurementMsg");
        $("#spanMeasurementMsg").css("display", "table-cell");
        if ($("#cnt3").css("display") == 'none')
            $("#" + shoppingStep).accordion('activate', 2);
        else
            ScrollToElement(_element2scroll);
        return false;
    }
    ok = true;
    $("#dvMeasurement" + rdMeasurement.val() + " input:text.measurement-value").each(function () {
        if (this.value == "") {
            ok = false;
            _element2scroll = document.getElementById("spanMeasurementMsg");
            $("#spanMeasurementMsg").css("display", "table-cell");
            $("#msg-" + this.id).css("display", "table-cell");
            if ($("#cnt3").css("display") == 'none')
                $("#" + shoppingStep).accordion('activate', 2);
            else
                ScrollToElement(_element2scroll);
            return false;
        }
        else {
            if ($(this).attr('alt') == 'd') {
                var x = parseFloat(this.value);
                if (isNaN(x)) {
                    ok = false;
                    _element2scroll = document.getElementById("spanMeasurementMsg");
                    $("#spanMeasurementMsg").css("display", "table-cell");
                    $("#msg-" + this.id).css("display", "table-cell");
                    if ($("#cnt3").css("display") == 'none')
                        $("#" + shoppingStep).accordion('activate', 2);
                    else
                        ScrollToElement(_element2scroll);
                    return false;
                }
                else {
                    this.value = x;
                }
            }
        }
    });
    /*
    if(ok)
    {
    $("#dvMeasurements div").each(function(n){
    if(this.id!="dvMeasurement" + rdMeasurement.val())
    $(this).remove();
    });
    }
    return ok;  
    */

    if (ok) {
        ////delete cookie
        ////var options = { path: '/', expires: 10/*, domain: null*/ };
        ////$.cookie('order_details', null, options);

        ////document.getElementById("btnNext").disabled='disabled';
        var jsonString = $.cookie('order_details');
        var ods;
        if (jsonString != null) {
            jsonString = "ods = " + jsonString;
            eval(jsonString);
        }
        if (ods == null) {
            ods = { "OrderDetails": [], "Express": false };
        }
        var od = {};
        od.id = guid();
        od.productid = queryString("id");
        od.quantity = 1;
        od.textileid = $("#hdTextiles").val();
        od.stylesadditionals = $("#txtAdditionalSpecifications").val();

        od.styles = getStyles();
        od.measurementid = getMeasurementId();
        od.measurements = getMeasurements();

        ods.OrderDetails.push(od);

        ////alert(JSON.stringify(ods));
        var options = { path: '/', expires: 1 };
        $.cookie('order_details', JSON.stringify(ods), options);
        ////alert($.cookie('order_details'));
        ////window.open("Cart.aspx", '_self');
        _submitted = true;
    }
    return ok;
};
function getStyles() {
    var styles = new Array();
    $("#divStyles input.styles").each(function (n) {
        var id = $(this).attr('id').slice(6);
        var svid = "style-value-" + id + "-" + $(this).val();
        var sdv = '';
        if (document.getElementById(svid) != null)
            sdv = $("#" + svid).val();
        var sd = { "id": $(this).val(), "value": sdv };
        styles.push(sd);
    });
    return styles;
};
function getMeasurementId() {
    var rdMeasurement = $("#dvMeasurements input:radio:checked");
    return rdMeasurement.val();
}
function getMeasurements() {
    var rdMeasurement = $("#dvMeasurements input:radio:checked");
    var measurements = new Array();
    $("#dvMeasurement" + rdMeasurement.val() + " input:text.measurement-value").each(function () {
        var id = $(this).attr('id');
        var index = id.lastIndexOf('-');
        id = id.substr(index + 1);
        var md = { "id": id, "value": $(this).val() };
        measurements.push(md);
    });
    return measurements;
}
function queryString(key) {
    var url = window.location.search.substring(1);
    var qs = url.split("&");
    for (var i = 0; i < qs.length; i++) {
        var q = qs[i].split("=");
        if (q[0] == key)
            return q[1];
    }
};
function cancelShopping() {
    var ods = $.JSONCookie('order_details');
    if (ods.OrderDetails == undefined)
        window.open("Home.aspx", '_self');
    else
        window.open("Cart.aspx", '_self');
};
function initMeasurements() {
    ////$("#dvMeasurements table:first").find("input:radio:first").attr('checked', 'checked');
    $("#dvMeasurements input:radio:first").attr('checked', 'checked');
    $("#dvMeasurements div:first").css("display", "");
    $("#dvMeasurements input:text.measurement-value").each(function () {
        ////$(this).mask($(this).attr('alt')=="d"?"999.99":$(this).attr('alt'));
        if ($(this).attr('alt') == 'd') {
            $(this).bind('keyup', function () {
                var x = parseFloat(this.value);
                if (isNaN(x))
                    $("#msg-" + this.id).css("display", "table-cell");
                else
                    $("#msg-" + this.id).css("display", "none");
            });
        }
        else
            $(this).mask($(this).attr('alt'));
    });

    ////$("#dvMeasurements input:text").bind("click", function(){
    ////    $("#spanMeasurementMsg").hide();
    ////});

    ////$("#dvMeasurements table:first input:radio").bind("click", function(){
    $("#dvMeasurements input:radio").bind("click", function () {
        var measurementid = $(this).val();
        select_measurement(measurementid);
    });
};
function select_measurement(measurementid) {
    var idMs = "dvMeasurement" + measurementid;
    if (document.getElementById(idMs) != null) {
        var div = $("#dvMeasurements");
        div.children().each(function () {
            if (this.tagName.toLowerCase() == "div") {
                if (this.id == idMs)
                    $(this).css("display", "");
                else
                    $(this).css("display", "none");
            }
        });
    }
}

function initStyles() {
    $("#divStyles input:text.style-value").each(function () {
        $(this).mask($(this).attr('alt') == "d" ? "999.99" : $(this).attr('alt'));
    });

    $("table.styles img").click(function () {
        var tableId = $(this).parent().parent().parent().parent().attr("id");
        $("table#" + tableId + " td").removeClass("SelectedItem");
        var styleid = $(this).attr('styleid');
        $("#spanStyleMsg" + styleid).css("display", "none");
        var val = $(this).attr('value');
        $("#styles" + styleid).val(val);
        $(this).parent().addClass("SelectedItem");
    });

    $("input.style-value").click(function () {
        var i = this.id.lastIndexOf('-');
        var sID = this.id.slice(i + 1);
        var j = this.id.lastIndexOf('-', i - 1);
        var SID = this.id.slice(j + 1, i);

        if ($("#styles" + SID).val() == sID) {
            $("#spanStyleMsg" + SID).css("display", "none");
        }
        ////alert(i + "\r\n" + j + "\r\n" + this.id + "\r\n" + sID+ "\r\n" + SID);
    });
};

function initTextiles() {
    $("a.paging").click(function () {
        if ($(this).hasClass('currentpage'))
            return;
        var clickedItem = $(this);
        var pageindex = $(this).text();
        var productid = getQuerystring('id', -1);

        function success_ws(data) {
            $("#dvTextiles").html(data);
            initTextileEvents();

            $("a.paging").removeClass('currentpage');
            clickedItem.addClass('currentpage');
            var textilesId = $("#hdTextiles").val();
            $("#img" + textilesId).parent().addClass("SelectedItem");
        };
        callWebServices("Textiles", "{productId: '" + productid + "', pageIndex: '" + pageindex + "'}", success_ws);
    });
    $('img.textiles').each(function (n) {
        ////this.alt='This is image['+n+'] with an id of '+this.id;
        var id = this.id;
        id = id.substr(3);
        if ($('#dv' + id).attr('imgsrc') != undefined) {
            $('#img' + id + "L").attr('src', 'CRFsImages/Textiles/' + $('#dv' + id).attr('imgsrc'));
            $('#dv' + id).removeAttr('imgsrc')
        }
        ////$('#dv' + id).css('display', 'block');
    });

    initTextileEvents();
};

function initTextileEvents() {
    $("img.textiles").click(function () {
        var id = this.id; //$(this).attr('id');
        id = id.substr(3);
        var parentid = $(this).parent().parent().parent().parent().attr('id');
        $('table#' + parentid + ' td').removeClass("SelectedItem");
        $(this).parent().addClass("SelectedItem");
        $("#hdTextiles").val(id);
        $("#msgTextiles").css("display", "none");
    });
    $("img.textiles").mousemove(function (e) {
        var id = this.id; //$(this).attr('id');
        id = id.substr(3);
        if ($('#dv' + id).attr('imgsrc') != undefined) {
            $('#img' + id + "L").attr('src', 'CRFsImages/Textiles/' + $('#dv' + id).attr('imgsrc'));
            $('#dv' + id).removeAttr('imgsrc')
        }
        if (!e) e = window.event;
        var vp = getViewport();
        var l = e.clientX + Math.max(document.body.scrollLeft, document.documentElement.scrollLeft);
        var t = e.clientY + Math.max(document.body.scrollTop, document.documentElement.scrollTop);
        if (l + 160 > vp.l + vp.w)
            l -= 160 + 5;
        else
            l += 5;
        if (t + 160 > vp.t + vp.h)
            t -= 160 + 5;
        else
            t += 5;
        $('#dv' + id).css('left', l);
        $('#dv' + id).css('top', t);
        $('#dv' + id).css('display', 'block');
    });
    $("img.textiles").mouseout(function () {
        var id = "#dv" + this.id.substr(3);
        $(id).css('display', 'none');
    });
};

function getViewport() {
    var m = document.compatMode == 'CSS1Compat';
    return {
        l: window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
        t: window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
        w: window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
        h: window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
    };
}

function loadCustomerMs(name, email) {
    var indexes = new Array();
    var checkedId = $("#dvMeasurements input:radio:checked").val();
    indexes.push(checkedId);
    $("#dvMeasurements input:radio:not(:checked)").each(function () {
        indexes.push(this.value)
    });
    var ms = "measurementIndexes : [";
    for (var i = 0; i < indexes.length; i++)
        ms += indexes[i] + ",";
    ms = ms.slice(0, ms.length - 1) + "]";
    function success_ws(data) {
        var json;
        eval("json = " + data);
        if (json.msDetails == null)
            alert("There is no your measurements in our database.");
        else {
            $("#rdMeasurement_" + json.measurementid).attr('checked', 'checked');
            select_measurement($("#rdMeasurement_" + json.measurementid).val());
            for (var i = 0; i < json.msDetails.length; i++)
                $("#measurement-value-" + json.measurementid + "-" + json.msDetails[i].id).val(json.msDetails[i].value);
        }
    }
    callWebServices("CustomerMeasurements", "{name: '" + name + "', email: '" + email + "'," + ms + "}", success_ws);
}

function callWebServices(webservice_method, string_data, success_method, error_method) {
    ShowProgressModal();
    $.ajax({
        type: "POST",
        url: "CRFsUserCtrl/CRFsServices.asmx/" + webservice_method,
        data: string_data, // "{name: 'a name'}" // "{}"
        contentType: "application/json; charset=utf-8",
        dataType: "json", //xml, html, script, json (msg.d), jsonp, text
        success: function (msg) {
            success_method(msg.d);
            HideProgressModal();
        },
        error: function (result) {
            if (error_method != null)
                error_method(result);
            else
                alert(result.status + ' ' + result.statusText);
            HideProgressModal();
        }
    })
}

function isValidEmail(sText) {
    var reEmail = /^(?:\w+\.?)*\w+@(?:\w+\.?)*\w+$/;
    return reEmail.test(sText);
}

function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
};
function S4() { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); }
function guid() { return (S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4()); }
////function guid() {   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());}

var _dvCustomerMs;
var _divModalProgress;
function ShowProgressModal() {
    _divModalProgress.modalShow();
    //$("#divModalProgress").modal().showModal();
};
function HideProgressModal() {
    _divModalProgress.modalHide();
    //$("#divModalProgress").modal().hideModal();
};
function showCustomerMs() {
    ////$("#dvCustomerMs").modal().showModal();
    _dvCustomerMs.modalShow();
    document.getElementById("txtName").focus();
};
function hideCustomerMs() {
    _dvCustomerMs.modalHide();
    ////$("#dvCustomerMs").modal().hideModal();
    $("#spanNameMsg").css("display", "none");
    $("#spanEmailMsg").css("display", "none");
};

function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent)
        while (1) {
            curleft += obj.offsetLeft;
            if (!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
else if (obj.x)
    curleft += obj.x;
return curleft;
}
function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent)
        while (1) {
            curtop += obj.offsetTop;
            if (!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
else if (obj.y)
    curtop += obj.y;
return curtop;
}
function ScrollToElement(theElement) {
    var selectedPosX = 0;
    var selectedPosY = 0;

    while (theElement != null) {
        ////selectedPosX += theElement.offsetLeft;
        selectedPosY += theElement.offsetTop;
        theElement = theElement.offsetParent;
    }

    window.scrollTo(selectedPosX, selectedPosY);
    _element2scroll = null;
}

function test_accordion() {
    //var index = $("#" + shoppingStep).accordion('option','active');
    //alert(index);
    //$("#" + shoppingStep).accordion( 'activate' , 0 )
    //var CurrentIdx = $("#" + shoppingStep + " h3").index($("#accordion h3.ui-state-active")); 
    //alert(CurrentIdx); 
}
