$(window).load(function ()
{
    /** jQuery Global Functions **/
    jQuery.char_limit_generic = function (item, item_limit, max, msg) 
    {
        var dlim = $(item_limit);
        var d = $(item);
        if (d.val().length > max) {
            d.val(d.val().substring(0, max));
        }
        var left = max - d.val().length;
        if (left <= 0) {
            left = 0;
            d.bubbleTip({
                message : msg
            });
        }
        dlim.empty().append(left);
    };
    jQuery.track_conv = function (label)
    {
        var google_conversion_id = AMD.gc_id;
        var google_conversion_label = label;
        image = new Image(1, 1);
        image.src = "http://www.googleadservices.com/pagead/conversion/" + google_conversion_id + "/?value=1&label=" + google_conversion_label + "&guid=ON&script=0";
    }
    jQuery.render_captcha = function () 
    {
        var cap_url = '/default/image/?sid=' + Math.floor(Math.random() * 10000);
        var captcha_placeholder = $('#ubox-container .captia');
        captcha_placeholder.html('');
        var image = $('<img />').attr('src', cap_url) .load(function () 
        {
            captcha_placeholder.append( $(this) );
        });
    };
    jQuery.show_register = function () 
    {
        if ($.ubox) 
        {
            $.ubox._oncomplete = function ()
            {
                s.pageName = 'My Account:Register';
                s.channel = "My Account Page";
                s.prop3 = "My Account Page";
                s.eVar18 = "No";
                s.t();
            };
            $.ubox("#ubox-register");
        }
    }
    jQuery.show_login = function () 
    {
        if ($.ubox) 
        {
            $.ubox._oncomplete = function ()
            {
                s.pageName = 'MyAccount:Login';
                s.channel = "My Account Page";
                s.prop3 = "My Account Page";
                s.eVar18 = "No";
                s.t();
                $("#login-username").focus();
            };
            $.ubox("#ubox-register");
        }
    }

	//sort selects
	jQuery.fn.sort = function()
	{
		return this.pushStack([].sort.apply(this, arguments), []);
	};

	jQuery.fn.sortOptions = function(sortCallback)
	{
		jQuery('option', this)
		.sort(sortCallback)
		.appendTo(this);
		return this;
	};

	jQuery.fn.sortOptionsByText = function()
	{
		var byTextSortCallback = function(x, y)
		{
			var xText = jQuery(x).text().toUpperCase();
			var yText = jQuery(y).text().toUpperCase();
			return (xText < yText) ? -1 : (xText > yText) ? 1 : 0;
		};
		return this.sortOptions(byTextSortCallback);
	};

	jQuery.fn.sortOptionsByValue = function()
	{
		var byValueSortCallback = function(x, y)
		{
			var xVal = jQuery(x).val();
			var yVal = jQuery(y).val();
			return (xVal < yVal) ? -1 : (xVal > yVal) ? 1 : 0;
		};

		return this.sortOptions(byValueSortCallback);
	};
});
/** Global Functions **/
var site_url;
var redirect;
var ajax_data;
var ajax_url;
var ubox_redirect;
var sitecatalyst_eval = '';
var adwords_label = '';
function global_init()
{
    site_url = "http://" + window.location.hostname;
    redirect = site_url + "/user/";
    ajax_data = '';
    ajax_url = '';
    ubox_redirect = false;
}
global_init();
function setCookie(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 getCookie(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;
}
function eraseCookie(name) 
{
    createCookie(name, "", - 1);
}
/* validate email address */
function validate_email(email)
{
    var regemail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    var regurl = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
    if (regemail.test(email) == false && email.length > 0) {
        return false;
    }
    return true;
}
/* javascript in_array */
function in_array(needle, haystack, argStrict) 
{
    var key = '', strict = !!argStrict;
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    }
    else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
    return false;
}
function sclinkCode(rsid, linkName, event, evar, prop, evarV) 
{
    var s = s_gi(rsid);
    s.linkTrackVars = '';
    s.linkTrackEvents = '';
    if (typeof (evar) != "undefined" && evar != null) 
    {
        for (i in evar) {
            s[i] = evar[i];
            if (s.linkTrackVars != '') {
                s.linkTrackVars += ',';
            }
            s.linkTrackVars += i;
        };
    }
    if (typeof (prop) != "undefined" && prop != null) 
    {
        for (i in prop) {
            s[i] = prop[i];
            if (s.linkTrackVars != '') {
                s.linkTrackVars += ',';
            }
            s.linkTrackVars += i;
        };
    }
    if (typeof (event) != "undefined" && event != null) 
    {
        if (s.linkTrackVars != '') {
            s.linkTrackVars += ',';
        }
        s.linkTrackVars += 'events';
        for (i = 0; i < event.length; i++) 
        {
            if (s.linkTrackEvents != '') {
                s.linkTrackEvents += ',';
                s.events += ',';
            }
            s.linkTrackEvents = event[i];
            s.events = event[i];
        };
    }
    if (s.linkTrackVars == '') {
        s.linkTrackVars = 'None';
    }
    if (s.linkTrackEvents == '') {
        s.linkTrackEvents = 'None';
    }
    s.tl(true, 'o', linkName);
    //alert(rsid+"\n"+s.linkTrackEvents+"\n"+s.linkTrackVars);    
}
function schandleOnclickEvent(s_account, url, event, evar, prop, desc, evarV, propV)
{
    var scevar = null;
    var scevent = null;
    var scprop = null;
    if (typeof (event) != "undefined" && event != null) {
        scevent = [];
        scevent[0] = event;
    }
    if (typeof (evar) != "undefined" && evar != null) 
    {
        scevar = [];
        if (typeof (evarV) != "undefined" && evarV != null) {
            scevar[evar] = evarV;
        }
        else {
            scevar[evar] = event;
        }
    }
    if (typeof (prop) != "undefined" && prop != null) 
    {
        scprop = [];
        if (typeof (propV) != "undefined" && propV != null) {
            scevar[prop] = propV;
        }
        else {
            scprop[prop] = event;
        }
    }
    sclinkCode(s_account, desc, scevent, scevar, scprop);
    window.location = url;
}
function scHandleClickSocialMediaLink(url, sm) 
{
    /** Set Analytics Data **/
    var prop = [];
    prop['prop35'] = s.channel + '|' + sm;
    var event = [];
    event[0] = 'event17';
    sclinkCode(s_account, sm, event, null, prop);
    /** Set Analytics Data **/
    window.open(url);
}
Array.prototype.indexOf = function (k)
{
    var len = this.length;
    for (i = 0; i < len; i++) {
        if (this [i] == k) {
            return i;
        }
    }
    return - 1;
}
/** Login **/
function submit_login(form, e)
{
    var email = $("#login-username");
    var password = $("#login-password");
    var error = false;
    $('#loginForm .login').attr('disabled', 'disabled');
    if (e.keyCode == 13) {
        return false;
    }
    if (!validate_email(email.val()) || email.val() == '')
    {
        email.bubbleTip({
            fade : true, message : "Please enter a valid email address."
        });
        error = true;
    }
    if (password.val() == '') {
        password.bubbleTip({
            fade : true, message : "Please enter a password."
        });
        error = true;
    }
    else if (password.val().length < 6)
    {
        password.bubbleTip({
            fade : true, message : "A password must be atleast six characters."
        });
        error = true;
    }
    /** Set Analytics Data **/
    var s = s_gi(s_account);
    s.linkTrackVars = 'events';
    s.linkTrackEvents = 'event2';
    s.events = 'event2';
    s.tl(true, 'o', 'Login');
    /** Set Analytics Data **/
    if (error) {
        $('#loginForm .login').removeAttr('disabled');
        return false;
    }
    var post = $(form).serialize();
    $.post($(form).attr('action'), post, function (data)
    {
        if (data.response != 'Success')
        {
            $('#login-password').bubbleTip({
                message : data.response
            }).val('');
            $('#loginForm .login').removeAttr('disabled');
        }
        else
        {
            if (ajax_data != '') 
            {
                $.ajax(
                {
                    type : 'post', url : ajax_url, data : ajax_data + '&userid=' + data.userid, dataType : 'json', 
                    async : false,
                    success : function ( data ) 
                    {
                        if (data.response == 'success') 
                        {
                            if (data.qna_view_question) {
                                redirect = data.qna_view_question;
                            }
                            else if (data.is_custom_msg) {
                                if (data.custom_msg) {
                                    alert(data.custom_msg);
                                }
                            }
                            else {
                                alert("Success! Thank you for making AutoMD better.");
                            }
                        }
                        else {
                            alert( data.response );
                        }
                        if (sitecatalyst_eval) 
                        {
                            eval(sitecatalyst_eval);
                            /* stop reposting values on ubox loads */
                            s.linkTrackVars = '';
                            s.linkTrackEvents = '';
                            s.prop3 = '';
                            s.events = '';
                            s.tl(this, 'o', '');
                        }
                    },
                    error : function () 
                    {
                        alert( "An error occured.\nPlease try again later." );
                    }
                });
            }
            if (adwords_label) {
                $.track_conv(adwords_label);
            }
            // checkpoint
            if ( check_session_vehicle() && !AMD.save_carpicker) 
            {
                var popup_add_vehicle = site_url + "/user/prompt_vehicles/";
                popup_add_vehicle += '?url=' + escape(redirect);
                $.ubox(popup_add_vehicle);
                return;
            }
            if (ubox_redirect) {
                $.ubox(redirect);
            }
            else if (redirect) {
                if (AMD.redirect) {
                    location = site_url + '/user/';
                }
                else {
                    location = redirect;
                }
            }
            else {
                location.reload();
            }
        }
    },
    "json");
    return false;
}
function check_session_vehicle() 
{
    var sid = Math.floor(Math.random() * 11);
    var ret_val = false;
    $.ajax(
    {
        url : "/user/check_vehicle_session/", type : "get", data : "vehicle=ask_save&sid=" + sid, dataType : "json", 
        async : false,
        success : function (data) 
        {
            if (data.response == "true") {
                ret_val = true;
            }
        }
    }); 
    return ret_val;
}
/** Retrieve Password **/
var attempt_counter = 1;
function submit_retrieve_password(form)
{
    var email = $("#forgot-email");
    if (!validate_email(email.val()) || email.val() == '') 
    {
        $("#submit_email").focus();
        email.bubbleTip({
            fade : true, message : "Please enter a valid email address."
        });
        return false;
    }
    $.post('/user/forgot_password/?action=reset', {
        email : email.val()
    },
    function (data) 
    {
        if (data.response == 'Okay') {
            $.ubox(site_url + "/user/forgot_password?action=sent");
        }
        else 
        {
            attempt_counter++;
            if (attempt_counter > 3) {
                $.ubox($('#lb-email-nf'));
            }
            else {
                $(email).bubbleTip({
                    message : data.response
                });
                $("#forgot-email").focus();
            }
        }
    },
    "json");
    return false;
}
function submit_registration(form, e)
{
    var post = $(form).serialize();
    var sc_page_name = '';
    var error = false;
    var req = $(form).find(".required");
    var email = $("#reg-email");
    var p1 = $("#reg-password");
    var p2 = $("#reg-password2");
    $('#registerForm .login').attr('disabled', 'disabled');
    if (e.keyCode == 13) {
        return false;
    }
    /** validation **/
    $(req).each(function ()
    {
        if ($(this).val() == '') {
            $(this).bubbleTip({
                fade : true, message : "This field is required."
            });
            error = true;
        }
    });
    if (!validate_email(email.val()) && email.val() != '')
    {
        email.bubbleTip({
            fade : true, message : "Please enter a valid email address."
        });
        error = true;
    }
    if (p1.val().length < 6 && p1.val() != '') 
    {
        p1.bubbleTip({
            fade : true, message : "A password must be atleast six characters."
        });
        error = true;
    }
    if (p2.val() != p1.val() && p2.val() != '') {
        p2.bubbleTip({
            fade : true, message : "Passwords do not match."
        });
        error = true;
    }
    if ($("#i_agree").attr("checked") == false)
    {
        $("#i_agree").bubbleTip({
            fade : true, message : "You must agree to the terms and policy."
        });
        error = true;
    }
    /** Set Analytics Data **/
    var s = s_gi(s_account);
    s.linkTrackVars = 'eVar16';
    s.linkTrackEvents = 'None';
    s.eVar16 = 'No';
    s.tl(true, 'o', 'Register');
    /** Set Analytics Data **/
    if (error) {
        return false;
    }
    else
    {
        $('#registerForm .login').removeAttr('disabled');
        $.post($(form).attr('action'), post, function (data)
        {
            if (data.error)
            {
                /** Set Analytics Data **/
                var s = s_gi(s_account);
                s.linkTrackVars = 'eVar16';
                s.linkTrackEvents = 'None';
                s.eVar16 = 'No';
                s.tl(true, 'o', 'Register');
                if (data.error == 'Invalid security code') 
                {
                    $("#registerForm #reg-captcha").bubbleTip({
                        message : 'Your text does not match the image.'
                    }).val('');
                    $('#registerForm .login').removeAttr('disabled');
                    $.render_captcha();
                }
                else if (data.error == 'Email address already exists.') 
                {
                    a = confirm('Email address already exists.\nWould you like to retrieve your password?');
                    if (a) 
                    {
                        $.post('/user/forgot_password/?action=reset', {
                            email : $("#email", form).val()
                        },
                        function (data) 
                        {
                            if (data.response == 'Okay') {
                                $.ubox(site_url + '/user/forgot_password/?action=sent');
                            }
                            else {
                                alert(data.response);
                                $('#registerForm .login').removeAttr('disabled');
                            }
                        },
                        "json");
                    }
                }
                else if (data.error == 'Not activated.') 
                {
                    $("#registerForm .email_address").bubbleTip(
                    {
                        message : 'The email provided is already registered, but has not been verified.<br\>Please verify your email address or <a href="javascript:;">contact support</a>.'
                    });
                    $('#registerForm .login').removeAttr('disabled');
                }
            }
            else 
            {
                /** Set Analytics Data **/
                var s = s_gi(s_account);
                s.linkTrackVars = 'eVar16,events';
                if (sc_page_name) {
                    s.linkTrackVars += ',eVar20';
                }
                s.linkTrackEvents = 'event1';
                s.eVar16 = 'Yes';
                if (sc_page_name != '') {
                    s.eVar20 = sc_page_name;
                }
                s.events = 'event1';
                s.tl(true, 'o', 'Register');
                var key = data.response.split('||');
                $.post('/user/send_activation',{to:email.val(),userid:key[0],token:key[1]}, function(e){});
                /** Pending Transaction will executes here **/
                if (ajax_data != '') 
                {
                    $.ajax(
                    {
                        type : 'post', url : ajax_url, data : ajax_data + '&userid=' + key[0], dataType : 'json', 
                        async : false,
                        success : function ( data ) 
                        {
                            if (data.response == 'success') {
                                if (data.qna_view_question) {
                                    redirect = data.qna_view_question;
                                }
                            }
                            else {
                                alert( data.response );
                            }
                            if (sitecatalyst_eval) 
                            {
                                eval(sitecatalyst_eval);
                                /* stop reposting values on ubox loads */
                                s.linkTrackVars = '';
                                s.linkTrackEvents = '';
                                s.prop3 = '';
                                s.events = '';
                                s.tl(this, 'o', '');
                            }
                        },
                        error : function () 
                        {
                            alert( "An error occured.\nPlease try again later." );
                        }
                    });
                }
                $.ubox(site_url + "/user/update_profile");
            }
        },
        "json");
    }
    return false;
}
function submit_feedback(form)
{
    var data = $(form).serialize();
    var page_question = $("#page-question").val();
    var email = $("#form-email");
    var err = false;
    data += '&question=' + page_question;
    if (!validate_email($(email).val()) || $(email).val() == '')
    {
        $("#form-email").bubbleTip({
            fade : true, message : 'Please enter a valid email address'
        });
        err = true;
    }
    else 
    {
        var emailSplit = email.val();
        var arrEmailSplit = emailSplit.split('@');
        if (arrEmailSplit[0].length > 64 || arrEmailSplit[1].length > 255) 
        {
            $("#form-email").bubbleTip({
                fade : true, message : 'Please enter a valid email address'
            });
            err = true;
        }
    }
    if ($("#form-f1").val() == '')
    {
        $("#form-f1").bubbleTip({
            fade : true, message : 'Please enter your comments/suggestions.'
        });
        err = true;
    }
    if (err) {
        return false
    }
    $.post(form.action, data, function (data)
    {
        if (data.response == 'Success')
        {
            $.track_conv('CMUlCL61wAEQ9MaO8QM');
            $.ubox(site_url + "/default/success?option=4");
            return false;
        }
        else if (data.response == 'Invalid security code') 
        {
            $("#feedback-captcha").bubbleTip({
                message : 'Your text does not match the image.'
            }).val('').focus();
            $.render_captcha();
            return false;
        }
        else {
            alert(data.response);
            return false;
        }
    },
    "json");
    return false;
}
function submit_shop_feedback(form)
{
    var data = $(form).serialize();
    var email = $("#sf-form-email");
    var err = false;
    if (!validate_email($(email).val()) || $(email).val() == '')
    {
        $(email).bubbleTip({
            fade : true, message : 'Please enter a valid email address'
        });
        err = true;
    }
    else 
    {
        var emailSplit = email.val();
        var arrEmailSplit = emailSplit.split('@');
        if (arrEmailSplit[0].length > 64 || arrEmailSplit[1].length > 255) 
        {
            $(email).bubbleTip({
                fade : true, message : 'Please enter a valid email address'
            });
            err = true;
        }
    }
    if ($("#sf-form-description").val() == '')
    {
        $("#sf-form-description").bubbleTip({
            fade : true, message : 'Please describe incorrect information.'
        });
        err = true;
    }
    if (err) {
        return false
    }
    $.post(form.action, data, function (data)
    {
        if (data.response == 'success') {
            $.ubox(site_url + "/default/success?option=5");
            return false;
        }
        else if (data.response == 'Invalid security code') 
        {
            $("#sf-feedback-captcha").bubbleTip({
                message : 'Your text does not match the image.'
            }).val('').focus();
            $.render_captcha();
            return false;
        }
        else {
            alert(data.response);
            return false;
        }
    },
    "json");
    return false;
}
function update_profile(form)
{
    var err_found = false;
    var rx = new RegExp("(www\.)?[a-zA-Z0-9-\.]+[\.]+([A-Za-z]{2,3})$");
        	
    if ($('#gender').val() == '' && $("#avatar").val() == '')
    {
        $('#avatar').bubbleTip({
            fade : true, message : "Please select your avatar."
        });
        err_found = true;
    }
    if ($("#profile-location").val() == '')
    {
        $("#profile-location").bubbleTip({
            fade : true, message : "Please enter your location."
        });
        err_found = true;
    }
    
    if (($("#profile-website").val() != 'Add a website for Facebook Profile') && !(rx.test($("#profile-website").val()))){
    	 $("#profile-website").bubbleTip({
            fade : true, message : "Please enter a valid webiste URL."
        });
        err_found = true;   	
    }
    
    if (err_found) {
        return false;
    }
    else
    {
     
    	if ($("#profile-location").val() == 'Location'){
    	 	$("#profile-location").val(''); 
    	}
    	if($("#about-me").val() == 'Tell AutoMD members a little about yourself'){
    		$("#about-me").val(''); 
    	}
    	if ($("#profile-website").val() == 'Add a website for Facebook Profile'){
    	 	$("#profile-website").val(''); 
    	}  	 
        $(form).attr({
            target : "upload_target"
        });
        $("#upload_target").load(function ()
        {
            var ret = frames['upload_target'].document.getElementsByTagName("body")[0].innerHTML;
            var data = eval("(" + ret + ")");
            if (!data.response.error) {
                $.ubox(site_url + "/default/success?option=6");
            }
            else {
                alert(data.response.error_message);
            }
        });
        return true;
    }
}