// Javascript code copyright 2009 by Fiach Reid : www.webtropy.com
// This code may be used freely, as long as this copyright notice is intact.
function Calculate(Luhn) {
    var sum = 0;
    for (i = 0; i < Luhn.length; i++) {
        sum += parseInt(Luhn.substring(i, i + 1));
    }
    var delta = new Array(0, 1, 2, 3, 4, -4, -3, -2, -1, 0);
    for (i = Luhn.length - 1; i >= 0; i -= 2) {
        var deltaIndex = parseInt(Luhn.substring(i, i + 1));
        var deltaValue = delta[deltaIndex];
        sum += deltaValue;
    }
    var mod10 = sum % 10;
    mod10 = 10 - mod10;
    if (mod10 == 10) {
        mod10 = 0;
    }
    return mod10;
}

function Validate(Luhn) {
    var LuhnDigit = parseInt(Luhn.substring(Luhn.length - 1, Luhn.length));
    var LuhnLess = Luhn.substring(0, Luhn.length - 1);
    if (Calculate(LuhnLess) == parseInt(LuhnDigit)) {
        return true;
    }
    return false;
}



$.extend({
    getUrlVars: function () {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function (name) {
        return $.getUrlVars()[name];
    }
});

$.fn.onClickClearField = function () {
    return this.focus(function () {
        if (this.value == this.defaultValue) {
            this.value = "";
        }
    }).blur(function () {
        if (!this.value.length) {
            this.value = this.defaultValue;
        }
    });
};

$.fn.validateEmail = function () {

    var hasError = false;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

    var emailaddressVal = $(this).val().toLowerCase();
    if (emailaddressVal == '') {
        hasError = true;
    }
    else if (!emailReg.test(emailaddressVal)) {
        hasError = true;
    }

    if (hasError == true) { return false; } else { return true; }
};


$(document).ready(function () {

    $('form#formwrapper').attr('autocomplete', 'off');
    $("form#formwrapper").submit(function (event) {
        //alert("form submitted");
        event.preventDefault();
    });

    //Any imag tags with no src should be given a default holding image src
    $("img[src='']").attr("src", "images/imagenotavailable.jpg");


    $('.toggleforms').click(function (event) {
        event.preventDefault();
        $('#loginformholder').toggle();
        $('#forgotpasswordformholder').toggle();
    });

	//some code to hide login and register boxes when outside div area is clicked
	mouseinsidereg=false;
	mouseinsidelog=false;
    $('#register_box').hover(function(){ 
		mouseinsidereg=true; 
    }, function(){ 
        mouseinsidereg=false; 
    });
    $('#login_box').hover(function(){
        mouseinsidelog=true; 
    }, function(){  
		mouseinsidelog=false; 
    });
    $("body").mouseup(function(){ 
        if(mouseinsidereg==false){
			if($('#register_box').is(':visible')){
				$('#register_box').toggle();
			}
		}
		if(mouseinsidelog==false){
			if($('#login_box').is(':visible')){
				$('#login_box').toggle();
			}
		}
    });


    $('#uber_login a.loginlink').click(function (event) {
		event.preventDefault();
		$('#register_box').css('display', "none");
        $('#login_box').toggle();
		$('#email').focus();
    });
	
	//this selects the first a in the li, eg the main link
    $('#uber_register a:first').click(function (event) {
		event.preventDefault();
        $('#login_box').css('display', "none");
        $('#register_box').toggle();
    });

    clear_input('q');

    $('#login_form input#email').onClickClearField();
    $('input#forgotemail').onClickClearField();
    $('input#password').onClickClearField();
	
	var relativeLocation = findRelativeBasePath();
	
    //Perform Login
    $('#uber_login input#login_submit').click(function (event) {
        event.preventDefault();
		$("div.waitingimg").show();
        didloginwork = Login($('#uber_login input#email').val(), $('#uber_login input#password').val());
        if (didloginwork == true) {
            $(window.location).attr('href', findRelativeBasePath() + "PanelGroup_AccountDetails.aspx");
        } else {
            $("div.waitingimg").hide();
			alert('Sorry, your login details are incorrect.');
        }
        return false;
    });

    $("#uber_login input#email").keypress(function (event) {
        if (event.which == 13) {
			$("div.waitingimg").show();
            didloginwork = Login($('#uber_login input#email').val(), $('#uber_login input#password').val());
            if (didloginwork == true) {
                $(window.location).attr('href', findRelativeBasePath() + "PanelGroup_AccountDetails.aspx");
            } else {
				$("div.waitingimg").hide();
                alert('Sorry, your login details are incorrect.');
            }
            return false;
        }
    });
    $("#uber_login input#password").keypress(function (event) {
        if (event.which == 13) {
			$("div.waitingimg").show();
            didloginwork = Login($('#uber_login input#email').val(), $('#uber_login input#password').val());
            if (didloginwork == true) {
                $(window.location).attr('href', findRelativeBasePath() + "PanelGroup_AccountDetails.aspx");
            } else {
				$("div.waitingimg").hide();
                alert('Sorry, your login details are incorrect.');
            }
            return false;
        }
    });

    //Perform Logout
    $('#uber_login a.logoutlink').click(function (event) {
        event.preventDefault();
        didlogoutwork = Logout();
        if (didlogoutwork == true) {
            $(window.location).attr('href', findRelativeBasePath() + "Home");
        } else {
            alert('Sorry, we where not able to log you out.');
        }
    });
    //Perform Logout
    $('a.logoutcmd').click(function (event) {
        event.preventDefault();
        didlogoutwork = Logout();
        if (didlogoutwork == true) {
           $(window.location).attr('href', findRelativeBasePath() + "Home");
        } else {
            alert('Sorry, we where not able to log you out.');
        }
    });

    $('a.logoutlink').click(function (event) {
        event.preventDefault();
        didlogoutwork = Logout();
        if (didlogoutwork == true) {
           $(window.location).attr('href', findRelativeBasePath() + "Home");
        } else {
            alert('Sorry, we where not able to log you out.');
        }
    });


    //perform check if logged in to control login logout buttons
    /*var isLoggedInDetails = {};
    var userDetails = {};

    //////////////////////////////////////////////////
    var result = ajaxServiceCall('WebServices/MonadelAccess.asmx/IsLoggedIn', isLoggedInDetails, "json", false);
    userDetails['varToRetrieve'] = 'UserName';

    if (typeof result != 'undefined') {
        //alert(result);
        if (result == true) {
            var whoami = ajaxServiceCall('WebServices/MonadelAccess.asmx/getUserVar', userDetails, "json", false);

            //alert("We are logged in");
            //show hide as required
            if ($("#uber_logout").is(":hidden")) {
                $("#uber_logout").toggle();
            }
            if ($("#uber_details").is(":hidden")) {
                $("#uber_details").toggle();
            }
            if ($("#uber_login").is(":visible")) {
                $("#uber_login").toggle();
            }
            if ($("#uber_register").is(":visible")) {
                $("#uber_register").toggle();
            }

            //If account details panel visible show user name
            if ($("#uber_details").is(":visible")) {
                $("#uber_details a.UsersName").text(whoami);
            }
        } else if (result == false) {
            //alert("We are not logged in");
            //show hide as required
            if ($("#uber_logout").is(":visible")) {
                $("#uber_logout").toggle();
            }
            if ($("#uber_details").is(":visible")) {
                $("#uber_details").toggle();
            }
            if ($("#uber_login").is(":hidden")) {
                $("#uber_login").toggle();
            }
            if ($("#uber_register").is(":hidden")) {
                $("#uber_register").toggle();
            }
        }
    }*/

    $('#uber_login input#forgot_submit').click(function () {
        if ($("#uber_login input#forgotemail").validateEmail() == true) {
            //redirect to set password page
            //document.location.href= "PanelGroup_SetPassword.aspx";
            $(window.location).attr('href', findRelativeBasePath() + "PanelGroup_SetPassword.aspx");
        } else {
            alert("This is not a valid email");
        }
    });

    $('#search').submit(function () {
        myValue = $("#q").val();
        // alert(myValue + "-" + myValue.length);
        if (myValue.length > 0) {
            myNewLocation = findRelativeBasePath() + "PanelGroup_Search.aspx?SearchText=" + myValue;
            $(location).attr('href', myNewLocation);
        }
        return false;
    });

    $("#q").keypress(function (event) {
        if (event.which == 13) {
            $("#searchahref").click();
            return false;
        }
    });

    $("#searchahref").click(function () {
        myValue = $("#q").val();
        //alert(myValue + "-" + myValue.length);
        if (myValue.length > 0) {
            myNewLocation = findRelativeBasePath() + "/PanelGroup_Search.aspx?SearchText=" + myValue;
            //alert(myNewLocation);
            $(window.location).attr('href', myNewLocation);
        }
    });

    function clear_input(field) {
        $("#" + field).focus(function () {
            myValue = $("#" + field).val();
            if (myValue == "Search") { $(this).val(""); }
        });
        $("#" + field).blur(function () {
            myValue = $("#" + field).val();
            if (myValue == "") { $(this).val("Search"); }
        });
    }
});

