﻿this.IE = $.browser.msie;
this.FF = $.browser.mozilla;

function $L(msg) {
    Web.WebServices.ClientTracer.Log({ Msg: msg });
}

(function($) {
    function init() {
        formTest(false);

        initEvents();
        fixAspFormForBaseTag();
    }
    function initEvents() {
        $.extend($.fn.disableTextSelect = function() {
            return this.each(function() {
                if ($.browser.mozilla) {//Firefox
                    $(this).css('MozUserSelect', 'none');
                } else if ($.browser.msie) {//IE
                    $(this).bind('selectstart', function() { return false; });
                } else {//Opera, etc.
                    $(this).mousedown(function() { return false; });
                }
            });
        });
        $('.noSelect').disableTextSelect(); //No text selection on elements with a class of 'noSelect'
    }
    function fixAspFormForBaseTag() {
        $("#aspnetForm").attr("action", window.location.href);
    }
    function getRandomString() {
        var s = [];
        var a = 'a'.charCodeAt();
        var z = 'z'.charCodeAt();

        for (var i = 0; i < 5; i++) {
            s.push(String.fromCharCode(Math.floor(Math.random() * (z - a)) + a));
        }
        return s.join("");
    }
    function getRandomDigit() {
        var s = [];
        var a = '0'.charCodeAt();
        var z = '9'.charCodeAt();

        for (var i = 0; i < 7; i++) {
            s.push(String.fromCharCode(Math.floor(Math.random() * (z - a)) + a));
        }
        return s.join("");
    }
    function formTest(enabled) {
        var email = "";
        var pass = "Aa1234";
        if (typeof (autoFillForms) != "undefined" && autoFillForms && enabled) {
            if (enabled) {
                var elements = $("input[type='text'],input[type='password'],input[type='radio'], select, textarea");
                elements.each(function(e) {
                    var inp = $(this);

                    var name = inp.attr("name").toLowerCase();
                    var el = { name: name, contains:
                    function(val) {
                        return this.name.indexOf(val.toLowerCase()) > -1;
                    }
                    };
                    if (inp.val().length > 1) return;

                    if (el.contains("txtFirstName")) {
                        inp.val("T E S T E R");
                    }
                    else
                        if (el.contains("txtMiddleName")) {
                        inp.val("Tester-MiddleName");
                    }
                    else
                        if (el.contains("txtSurname")) {
                        inp.val("Tester-Surname");
                    }
                    else
                        if (el.contains("dropCountry")) {
                        inp.val("Togo");
                    }
                    else
                        if (el.contains("dropSign")) {
                        inp.val("2/6/2010");
                    }
                    else
                        if (el.contains("ddlAcceptResolution1") ||
                           el.contains("ddlAcceptResolution2") ||
                           el.contains("ddlAcceptResolution3") ||
                           el.contains("ddlAcceptResolution4")) {
                        inp.val("1");
                    }
                    else {
                        inp.val(getRandomString());
                    }
                });
            }
        }
    }
    function contains(val) {
    }

    $(document).ready(function() {
        init();
        Site.init();
    });

    Site = {
        chatAdminPopup: null,
        ResourcesJs: null,

        init: function() {
            this.initExtendedValidators();
            this.setValidator();
            this.ResourcesJs = new jQuery.Hashtable();
        },
        loadjscssfile: function(filename, filetype) {
            if (filetype == "js") { //if filename is a external JavaScript file
                var fileref = document.createElement('script')
                fileref.setAttribute("type", "text/javascript")
                fileref.setAttribute("src", filename)
            }
            else if (filetype == "css") { //if filename is an external CSS file
                var fileref = document.createElement("link")
                fileref.setAttribute("rel", "stylesheet")
                fileref.setAttribute("type", "text/css")
                fileref.setAttribute("href", filename)
            }
            if (typeof fileref != "undefined") {
                document.getElementsByTagName("head")[0].appendChild(fileref)
            }
        },
        RegisterJs: function(url, key) {
            var script = Site.ResourcesJs.get(key);
            if (script) {
                $(script).remove();
                Site.ResourcesJs.remove(key);
            }
            script = document.createElement("script");
            script.src = url;

            Site.ResourcesJs.add(key, script);

            document.body.appendChild(script);
        },
        OpenAdminChat: function() {
            if (Site.chatAdminPopup == null) {
                var url = lang + "/chat.aspx?mode=ChatAdmin";

                Site.chatAdminPopup = windowOpener(516, 516, "GuestsQueue", url);

                if (Site.chatAdminPopup) {
                    Site.chatAdminPopup.focus();
                }
            }
        },
        initExtendedValidators: function() {

            $.validator.addMethod("password", function(pass, element) {
                return !this.optional(element) && pass.match(/^\s*\w*(?=.{5,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w*\s*$/);
            }, "Password must contain at least one capital letter. Check if you pasted the pass with trailing spaces of was on the CapsLock");

            $.validator.addMethod("emailButAllowTrailingWhitespace", function(value, element) {
                return (this.optional(element) || jQuery.validator.methods.email.call(this, jQuery.trim(value), element));
            }, "Please enter a valid email");
        },
        setValidator: function(options) {
            Site.Validator = $("#aspnetForm").bind("invalid-form.validate", function(a, b) {
                var topErrorElement = b.errorList[0].element
                $.scrollTo(topErrorElement, "slow");
                topErrorElement.focus();
            }).validate({
                meta: "validate",
                debug: false,
                errorPlacement: function(error, element) {
                    error.appendTo(element.parent().find(".error-can"));
                },
                focusInvalid: true,
                onkeyup: function(error, element) {
                },
                submitHandler: function(form, a) {
                    form.submit();
                },
                success: function(label) {
                }
            });
        },
        CheckEmailAvailability: function(value, type, provider) {
            var result = false;
            $.ajax({
                dataType: 'json',
                async: false,
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: "{ Email: '" + value + "', type: '" + type + "', provider: '" + provider + "' }",
                url: 'WebServices/Registration_WS.asmx/CheckEmailAvailability',
                success: function(response) {
                    result = response.d;
                }
            });
            return result;
        },
        ShowFormOverlay: function() {
            var overlayPanel = $("#overlay-panel");

            if (overlayPanel) {
                var overlay = overlayPanel.find(".overlay");
                var container = overlayPanel.parents(".main");
                overlay.height(container.height());
                overlay.width(container.width());
                overlayPanel.show();
            }
        }
    };
})(jQuery);

function clickPDFBtn() {
    var iFrame = window.document.getElementById('TB_iframeContent');
    iFrame.contentWindow.document.getElementById('btnToPDF').click();
}
function isCookieEnabled() {
    var cookieEnabled = (navigator.cookieEnabled) ? true : false;

    //if navigator,cookieEnabled is not supported
    if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
        document.cookie = "testcookie";
        cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
    }

    if (!cookieEnabled)
        window.open("Cookie.htm");
}
function sortTable(obj, func) {

    var tBody = obj.parentNode.parentNode.parentNode;
    var pass = 1, exchanges = true, tmpRow;

    while (pass < tBody.rows.length && exchanges) {
        exchanges = false;
        //0index row is header
        for (var i = 1; i < tBody.rows.length - pass; i++) {
            if (obj.getAttribute("order") == "asc") {
                //Exchange
                if (eval(func + "(tBody.rows[i],tBody.rows[i + 1])") > 0) {
                    swapNodes(tBody.rows[i], tBody.rows[i + 1]);
                    exchanges = true;
                }
            }
            else {
                //Exchange
                if (eval(func + "(tBody.rows[i],tBody.rows[i + 1])") < 0) {
                    swapNodes(tBody.rows[i], tBody.rows[i + 1]);
                    exchanges = true;
                }
            }
        }
        ++pass;
    }
    obj.setAttribute("order", (obj.getAttribute("order") == "asc" ? "desc" : "asc"));
}
function swapNodes(item1, item2) {
    //Clone node that will be swaped
    var itemtmp = item1.cloneNode(1);
    var parent = item1.parentNode;

    //Replace 2nd node with the copy of the 1st node
    // which returns the new node
    item2 = parent.replaceChild(itemtmp, item2);
    //Replace the 1st node with the new 2nd node
    parent.replaceChild(item2, item1);

    // And finally replace the first item with it's copy so that we
    // still use the old nodes but in the new order. This is the reason
    // we don't need to update our Behaviours since we still have
    // the same nodes.
    parent.replaceChild(item1, itemtmp);

    // Free up some memory
    itemtmp = null;
}
function createCookie(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 + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

//For IE,safari
if (typeof (DOMParser) == 'undefined') {
    DOMParser = function() { }
    DOMParser.prototype.parseFromString = function(str, contentType) {
        if (typeof (ActiveXObject) != 'undefined') {
            var xmldata = new ActiveXObject('MSXML.DomDocument');
            xmldata.async = false;
            xmldata.loadXML(str);
            return xmldata;
        } else if (typeof (XMLHttpRequest) != 'undefined') {
            var xmldata = new XMLHttpRequest;
            if (!contentType) {
                contentType = 'application/xml';
            }
            xmldata.open('GET', 'data:' + contentType + ';charset=utf-8,' + encodeURIComponent(str), false);
            if (xmldata.overrideMimeType) {
                xmldata.overrideMimeType(contentType);
            }
            xmldata.send(null);
            return xmldata.responseXML;
        }
    }
}
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

function JumpToAnchor(obj) {
    location.href = obj.options[obj.selectedIndex].value;
}

function windowOpener(width, height, windowName, windowUri) {
    var centerWidth = (window.screen.width - width) / 2;
    var centerHeight = (window.screen.height - height) / 2;
    newWindow = window.open(windowUri, windowName, 'status=1, location=1, resizable=1, width=' + width + ', height=' + height + ',left=' + centerWidth + ',top=' + centerHeight);
    newWindow.focus();
    return newWindow;
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + exdate.toGMTString());
}
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 capsLock(e) {
    kc = e.keyCode ? e.keyCode : e.which;
    sk = e.shiftKey ? e.shiftKey : ((kc == 16) ? true : false);
    if (((kc >= 65 && kc <= 90) && !sk) || ((kc >= 97 && kc <= 122) && sk)) {
        var msg = 'Caps Lock is On.\n\nTo prevent entering your password incorrectly,\nyou should press Caps Lock to turn it off.';
        alert(msg);
    }
}

