var mstrLastEnquiryEmail = "";
var mstrLastEnquiryMessage = "";
var mboolPasswordResetInProgress = false;

//***************** Active Menu Highlight ************************
function scriptInit()
{
    if (!document.getElementById)
    {
        return;
    }
}

//assigning checkActive function to window as addEventListener, or attachEvent, or event
function addEvent(elm, evType, fn, useCapture)
{

    try
    {

        if (elm.addEventListener)
        {
            elm.addEventListener(evType, fn, useCapture);
            return true;
        }
        else if (elm.attachEvent)
        {
            var r = elm.attachEvent('on' + evType, fn);
            return r;
        }
        else
        {
            elm['on' + evType] = fn;
        }

    }
    catch (Error)
    {
        //document.location.href = "Error.aspx?Module=GlobalScript.js&Method=addEvent&Message=Error trying to load page";
    }

}

//checkActive will go thru all the menu items and get the current windows href and set that particular link as active.
function checkActive()
{

    try
    {

        var lilist = document.getElementById('mainmenu');
        var alink = lilist.getElementsByTagName("a");
        var loc = null;
        if (window.location.href.substr(location.href.length - 1, 1) == '/')
        {
            //if no file specified for the url, then append default page name.
            loc = window.location.href + _ctrlDefaultPageUrl.value; // 'default.aspx';
        }
        else
        {
            loc = window.location.href;
        }

        for (var i = 0; i < alink.length; i++)
        {
            if ((loc.indexOf("customer-profile.aspx") != -1 || loc.indexOf("supplier-profile.aspx") != -1) && alink[i].href.indexOf("profile.aspx") != -1)
            {
                alink[i].setAttribute("class", "active");
                alink[i].setAttribute("className", "active");
            }
            else
            {
                if (loc == alink[i].href)
                {
                    alink[i].setAttribute("class", "active");
                    alink[i].setAttribute("className", "active");
                    //break;
                }
                else
                {
                    alink[i].setAttribute("class", "");
                    alink[i].setAttribute("className", "");
                }
            }
        }
    }
    catch (Error)
    {
        //document.location.href = "default.aspx";
    }

}

// add load event to 
addEvent(window, 'load', checkActive, false);

//***************** End Active Menu Highlight script************************

$(document).ready(function () {
    Cufon.replace('.nav li strong', { fontFamily: 'MyriadPro', hover: true });
    Cufon.replace('.MyriadPro', { fontFamily: 'MyriadPro', hover: true });

    $("#site-body").show();
    //setTimeout('$("#site-body").show();', 10);

    $(".form :input[type='text'],.form :input[type='password']").wijtextbox();

    $(".lightbox").lightbox({
        fileLoadingImage: 'images/loadingAnimation.gif',
        fileBottomNavCloseImage: 'images/closeimg.png',
        overlayOpacity: 0.8,
        borderSize: 10,
        imageArray: new Array,
        activeImage: null,
        inprogress: false,
        resizeSpeed: 350,
        widthCurrent: 250,
        heightCurrent: 250,
        xScale: 1,
        yScale: 1,
        displayTitle: true,
        navbarOnTop: false,
        slideNavBar: false, // slide nav bar up/down between image resizing transitions
        navBarSlideSpeed: 350,
        displayHelp: false,
        strings: {
            help: ' \u2190 / P - previous image\u00a0\u00a0\u00a0\u00a0\u2192 / N - next image\u00a0\u00a0\u00a0\u00a0ESC / X - close image gallery',
            prevLinkTitle: 'previous image',
            nextLinkTitle: 'next image',
            prevLinkText: '&laquo; Previous',
            nextLinkText: 'Next &raquo;',
            closeTitle: 'close image gallery',
            image: 'Image ',
            of: ' of '
        },
        fitToScreen: false, 	// resize images if they are bigger than window
        disableNavbarLinks: false,
        loopImages: false,
        imageClickClose: false,
        jsonData: null,
        jsonDataParser: null
    });

    if ($(window).width() < 1680) {
        $('.container').css('left', '-' + (1680 - $(window).width()) / 2 + 'px');
        $(window).scroll(function () {
            //$('.container').css('left', '-' + (1680 - $(window).width()) / 2 + 'px');
        });
    }

    if ($.browser.msie && (parseInt($.browser.version) <= 7)) {
        try {
            document.execCommand('BackgroundImageCache', false, true);
        } catch (e) { }
        $('input').hover(function () {
            $(this).addClass('hover');
        }, function () {
            $(this).removeClass('hover');
        });
    }
    if (window.navigator.userAgent.indexOf('Chrome') !== -1) {
        $('html').css('-webkit-text-size-adjust', 'none');
    }
    $('a[rel="external"]').attr('target', '_blank');

    // Login popup
    $("#login-popup").wijdialog({
        autoOpen: false,
        height: 400,
        width: 350,
        modal: true,
        resizable: false,
        buttons: {
            Register: function () {
                document.location.href = "user-subscribe.aspx";
            },
            Login: function () {
                Auth();
            },
            Cancel: function () {
                $(this).wijdialog("close");
            }
        },
        captionButtons: {
            pin: { visible: false },
            refresh: { visible: false },
            toggle: { visible: false },
            minimize: { visible: false },
            maximize: { visible: false }
        },
        open: function () {
            $("#RememberMe").wijcheckbox("destroy").wijcheckbox();
        },
        close: function () {
            //allFields.val("").removeClass("ui-state-error"); // Need to implement clearing of the text boxes manually
        }
    });

    $("div[aria-labelledby='ui-dialog-title-login-popup'] button:first-child").css("margin-right", "82px"); // Sets the first button to the left

    $("#UserName").keyup(function (e) {
        var e = window.event || e;
        var keyUnicode = e.charCode || e.keyCode;
        if (e !== undefined) {
            if (keyUnicode == 13) {
                $("#Password").focus();
            }
        }
    });

    $("#Password").keyup(function (e) {
        var e = window.event || e;
        var keyUnicode = e.charCode || e.keyCode;
        if (e !== undefined) {
            if (keyUnicode == 13) {
                Auth();
            }
        }
    });

    $(".login").click(function () {
        $("#login-popup").wijdialog("open");
    });

    $("#cmdEnquire").click(function (e) {
        if ($("#EnquiryMessage").val() != mstrLastEnquiryMessage || $("#EnquiryEmail").val() != mstrLastEnquiryEmail) {

            mstrLastEnquiryEmail = $("#EnquiryEmail").val();
            mstrLastEnquiryMessage = $("#EnquiryMessage").val();

            var bValid = true;

            bValid = bValid && checkLength($("#EnquiryMessage"), "message", 1, 1000, $(".enquirytips"));
            bValid = bValid && $("#EnquiryMessage").val() != "Your Message";
            bValid = bValid && checkLength($("#EnquiryEmail"), "email", 6, 80, $(".enquirytips"));
            bValid = bValid && checkRegexp($("#EnquiryEmail"), /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Please provide correct email address", $(".enquirytips"));

            if (bValid) {
                $("body").css("cursor", "progress");
                $(".form").css("cursor", "progress");

                Main_Website.DataService.SendEnquiry($("#EnquiryEmail").val(), $("#EnquiryMessage").val(), onEnquirySuccess, onFailAuth)

            }

        }

        e.preventDefault();
    });

    $("#cmdPasswordReset, #cmdPasswordResetCancel").button();

    $("#cmdPasswordReset").click(function () {
        if (!mboolPasswordResetInProgress) {
            mboolPasswordResetInProgress = true;

            $("body").css("cursor", "progress");
            $(".form").css("cursor", "progress");

            Main_Website.DataService.ResetPassword($("#password-reset-email").val(), onPassResetSuccess, onFailAuth);
        }
    });

    $("#cmdPasswordResetCancel").click(function () {
        document.location.href = "default.aspx";
    });

    $("#diagram_extract").tooltip({
        effect: 'fade',
        position: 'center right',
        relative: true
    });

    $("#diagram_integrate").tooltip({
        effect: 'fade',
        position: 'center left',
        relative: true
    });

    $("#diagram_transform").tooltip({
        effect: 'fade',
        position: 'center left',
        relative: true
    });

    // Init the video lightboxes
    $(".prettyLB").prettyPhoto({
        animation_speed: 'slow', /* fast/slow/normal */
        slideshow: 5000, /* false OR interval time in ms */
        autoplay_slideshow: false, /* true/false */
        opacity: 0.80, /* Value between 0 and 1 */
        show_title: false, /* true/false */
        allow_resize: true, /* Resize the photos bigger than viewport. true/false */
        default_width: 897,
        default_height: 500,
        counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
        theme: 'pp_default', //'pp_default', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
        horizontal_padding: 20, /* The padding on each side of the picture */
        hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
        wmode: 'opaque', /* Set the flash wmode attribute */
        autoplay: true, /* Automatically start videos: True/False */
        modal: true, /* If set to true, only the close button will close the window */
        deeplinking: true, /* Allow prettyPhoto to update the url to enable deeplinking. */
        overlay_gallery: true, /* If set to true, a gallery will overlay the fullscreen image on mouse over */
        keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */
        changepicturecallback: function () { }, /* Called everytime an item is shown/changed */
        callback: function () { }, /* Called when prettyPhoto is closed */
        ie6_fallback: true,
        social_tools: false //<div class="pp_social"><div class="twitter"><a href="http://twitter.com/share" class="twitter-share-button" data-count="none">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="facebook"><iframe src="http://www.facebook.com/plugins/like.php?locale=en_US&href=' + location.href + '&amp;layout=button_count&amp;show_faces=true&amp;width=500&amp;action=like&amp;font&amp;colorscheme=light&amp;height=23" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:500px; height:23px;" allowTransparency="true"></iframe></div></div>' /* html or false to disable */
    });

});

function onPassResetSuccess(result)
{
    $("body").css("cursor", "auto");
    $(".form").css("cursor", "auto");

    mboolPasswordResetInProgress = false;

    if (result > 0)
        updateTips($(".password-reset-result"), "Successfully reset password(s) for " + result + " account(s)");
    else if (result == 0)
        updateTips($(".password-reset-result"), "No accounts have been found for the given email address");
    else
        updateTips($(".password-reset-result"), "The email you have provided is invalid");
}

function onEnquirySuccess(result)
{
    $("body").css("cursor", "auto");
    $(".form").css("cursor", "auto");
    updateTips($(".enquirytips"), "Enquiry submitted");
}

function Auth()
{
    $("body").css("cursor", "progress");
    $(".form").css("cursor", "progress");

    mboolPasswordResetInProgress = false;

    Main_Website.DataService.Auth($("#UserName").val(), $("#Password").val(), $("#RememberMe")[0].checked, document.location.href, onSuccessAuth, onFailAuth);
}

function onSuccessAuth(result)
{

    try
    {

        $("body").css("cursor", "auto");
        $(".form").css("cursor", "auto");

        if (result > 0)
        {

            switchLoggedInMenuState(true, result);

            if ($.url.param("ReturnUrl") == "" || $.url.param("ReturnUrl") == 'undefined' || $.url.param("ReturnUrl") == null)
            {
                updateTips($(".validateTipsLogin"), "Redirecting to members page..");
                switch (result)
                {
                    case 1: document.location.href = "downloads-workQ.aspx"; //"customer-profile.aspx";
                        break;

                    case 2: document.location.href = "supplier-profile.aspx";
                        break;

                    case 3: document.location.href = "admin-profile.aspx";
                        break;

                    case 4: document.location.href = "default-supplier.aspx"; // Supplier registered but not yet subscribed so redirect to supplier landing page (which is their home)
                        break;

                    default: document.location.href = "Error.aspx?Module=GlobalScript.js&Method=Authenticate&Message=Error trying to authenticate";
                        break;

                }
            }
            else
            {
                var redirectUrl = decodeURIComponent($.url.param("ReturnUrl")) + "?" + $.url.attr("query").replace("&ReturnUrl=" + $.url.param("ReturnUrl"), "").replace("ReturnUrl=" + $.url.param("ReturnUrl") + "&", "").replace("ReturnUrl=" + $.url.param("ReturnUrl"), "");

                if (redirectUrl.endsWith("?"))
                    redirectUrl = redirectUrl.replace("?", "");

                if (redirectUrl.indexOf(".aspx") != -1 || redirectUrl.indexOf(".asp") != -1 || redirectUrl.indexOf(".html") != -1 || redirectUrl.indexOf(".htm") != -1 || redirectUrl.indexOf(".ashx") != -1)
                {
                    updateTips($(".validateTipsLogin"), "Redirecting to requested page..");
                    document.location.href = redirectUrl;
                }
                else
                {
                    updateTips($(".validateTipsLogin"), "Retrieving requested document..");
                    setTimeout("$('#login-popup').wijdialog('close'); popupDocumentRequest('" + $.url.attr("base") + redirectUrl + "');", 1000);
                }
            }
        }
        else if (result == -1)
            updateTips($(".validateTipsLogin"), "Your account has not yet been activated. Please click on the link in the account confirmation email we've sent you.");
        else if (result == -2)
            updateTips($(".validateTipsLogin"), "Your account has been locked out. Please contact support.");
        else
        {
            switchLoggedInMenuState(false, result);
            updateTips($(".validateTipsLogin"), "Your login attempt was unsuccessful");
        }
    }
    catch (Error)
    {
        document.location.href = "default.aspx";  //"Error.aspx?Module=GlobalScript.js&Method=Authenticate&Message=Error trying to authenticate";
    }

}

function onFailAuth(errors, userContext, methodName)
{
    $("body").css("cursor", "auto");
    $(".form").css("cursor", "auto");

    if (IsRedirectToLoginStatusCode(errors._statusCode) == true)
    {
        document.location.href = getRedirectURL(document.location.toString())
    }
    else
    {
        document.location.href = "default.aspx";  //"Error.aspx?Module=supplier-profile.js&Method=" + methodName + "&Message=" + errors._message;
    }

}

function switchLoggedInMenuState(isLoggedIn, mode)
{
    try
    {
        if (isLoggedIn == "True" || isLoggedIn == "true" || isLoggedIn == true)
        {
            $(".buttonLoginPopup").attr("src", "images/logout-button.gif")
            .unbind("click")
            .click(function ()
            {
                //alert("You are being logged out.."); // Just for testing
                PerformLogout();
            });

            if (mode == 1)
            {
                $("#menuProfile").attr("href", "customer-profile.aspx");
                $(".menuDefault").attr("href", _ctrlDefaultPageUrl.value); //"default.aspx");
            }
            else if (mode == 2 || mode == 4)
            {
                $("#menuProfile").attr("href", "supplier-profile.aspx");
                $(".menuDefault").attr("href", "default-supplier.aspx"); // Suppliers have a diffeent home page
            }
            if (mode == 3)
            {
                $("#menuProfile").attr("href", "admin-profile.aspx");
                $(".menuDefault").attr("href", _ctrlDefaultPageUrl.value); //"default.aspx");
            }

            $("#menuProfile").toggle(true);

            _ctrlIsLoggedIn.value = "True" // So that the page doesnt have to be refreshed prior to users trying to access documents
        }
        else
        {
            $(".buttonLoginPopup").attr("src", "images/login-button.gif")
            .unbind("click")
            .click(function ()
            {
                $("#login-popup").wijdialog("open");
            });

            $("#menuProfile").toggle(false);
            $(".menuDefault").attr("href", "default.aspx"); //_ctrlDefaultPageUrl.value);

            //_ctrlIsLoggedIn.value = "False"
        }
    }
    catch (Error)
    {
        document.location.href = "default.aspx";  //"Error.aspx?Module=GlobalScript.js&Method=switchLoggedInMenuState&Message=Error trying to switch logged in menu state";
    }
}



function updateTips(tips, t, html)
{
    if (html)
    {
        tips
				.html(html)
				.addClass("ui-state-highlight");
    }
    else
    {
        tips
				.text(t)
				.addClass("ui-state-highlight");
    }
    setTimeout(function ()
    {
        tips.removeClass("ui-state-highlight", 1500);
    }, 500);
}

function checkLength(o, n, min, max, tips)
{
    if (o.val().length > max || o.val().length < min)
    {
        o.addClass("ui-state-error");
        updateTips(tips, "Length of " + n + " must be between " +
					min + " and " + max + ".");
        return false;
    } else
    {
        return true;
    }
}

function checkRegexp(o, regexp, n, tips)
{
    if (!(regexp.test(o.val())))
    {
        o.addClass("ui-state-error");
        updateTips(tips, n);
        return false;
    } else
    {
        return true;
    }
}

function checkPasswordsMatch(password, password2, tips)
{
    if (!(password.val() == password2.val()))
    {
        password2.addClass("ui-state-error");
        updateTips(tips, "Passwords must match.");
        return false;
    } else
    {
        return true;
    }
}

/* jQuery Query String plugin */
// Written by Mark Perkins, mark@allmarkedup.com
// License: http://unlicense.org/ (i.e. do what you want with it!)

jQuery.url = function ()
{
    var segments = {};

    var parsed = {};

    /**
    * Options object. Only the URI and strictMode values can be changed via the setters below.
    */
    var options = {

        url: window.location, // default URI is the page in which the script is running

        strictMode: false, // 'loose' parsing by default

        key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"], // keys available to query 

        q: {
            name: "queryKey",
            parser: /(?:^|&)([^&=]*)=?([^&]*)/g
        },

        parser: {
            strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,  //less intuitive, more accurate to the specs
            loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
        }

    };

    /**
    * Deals with the parsing of the URI according to the regex above.
    * Written by Steven Levithan - see credits at top.
    */
    var parseUri = function ()
    {
        str = decodeURI(options.url);

        var m = options.parser[options.strictMode ? "strict" : "loose"].exec(str);
        var uri = {};
        var i = 14;

        while (i--)
        {
            uri[options.key[i]] = m[i] || "";
        }

        uri[options.q.name] = {};
        uri[options.key[12]].replace(options.q.parser, function ($0, $1, $2)
        {
            if ($1)
            {
                uri[options.q.name][$1] = $2;
            }
        });

        return uri;
    };

    /**
    * Returns the value of the passed in key from the parsed URI.
    * 
    * @param string key The key whose value is required
    */
    var key = function (key)
    {
        if (jQuery.isEmptyObject(parsed))
        {
            setUp(); // if the URI has not been parsed yet then do this first...	
        }
        if (key == "base")
        {
            if (parsed.port !== null && parsed.port !== "")
            {
                return parsed.protocol + "://" + parsed.host + ":" + parsed.port + "/";
            }
            else
            {
                return parsed.protocol + "://" + parsed.host + "/";
            }
        }

        return (parsed[key] === "") ? null : parsed[key];
    };

    /**
    * Returns the value of the required query string parameter.
    * 
    * @param string item The parameter whose value is required
    */
    var param = function (item)
    {
        if (jQuery.isEmptyObject(parsed))
        {
            setUp(); // if the URI has not been parsed yet then do this first...	
        }
        return (parsed.queryKey[item] === null) ? null : parsed.queryKey[item];
    };

    /**
    * 'Constructor' (not really!) function.
    *  Called whenever the URI changes to kick off re-parsing of the URI and splitting it up into segments. 
    */
    var setUp = function ()
    {
        parsed = parseUri();

        getSegments();
    };

    /**
    * Splits up the body of the URI into segments (i.e. sections delimited by '/')
    */
    var getSegments = function ()
    {
        var p = parsed.path;
        segments = []; // clear out segments array
        segments = parsed.path.length == 1 ? {} : (p.charAt(p.length - 1) == "/" ? p.substring(1, p.length - 1) : path = p.substring(1)).split("/");
    };

    return {

        /**
        * Sets the parsing mode - either strict or loose. Set to loose by default.
        *
        * @param string mode The mode to set the parser to. Anything apart from a value of 'strict' will set it to loose!
        */
        setMode: function (mode)
        {
            options.strictMode = mode == "strict" ? true : false;
            return this;
        },

        /**
        * Sets URI to parse if you don't want to to parse the current page's URI.
        * Calling the function with no value for newUri resets it to the current page's URI.
        *
        * @param string newUri The URI to parse.
        */
        setUrl: function (newUri)
        {
            options.url = newUri === undefined ? window.location : newUri;
            setUp();
            return this;
        },

        /**
        * Returns the value of the specified URI segment. Segments are numbered from 1 to the number of segments.
        * For example the URI http://test.com/about/company/ segment(1) would return 'about'.
        *
        * If no integer is passed into the function it returns the number of segments in the URI.
        *
        * @param int pos The position of the segment to return. Can be empty.
        */
        segment: function (pos)
        {
            if (jQuery.isEmptyObject(parsed))
            {
                setUp(); // if the URI has not been parsed yet then do this first...	
            }
            if (pos === undefined)
            {
                return segments.length;
            }
            return (segments[pos] === "" || segments[pos] === undefined) ? null : segments[pos];
        },

        attr: key, // provides public access to private 'key' function - see above

        param: param // provides public access to private 'param' function - see above

    };

} ();

