///////////////////////////////////////
// user
///////////////////////////////////////
var _user = {
    userdata               : {},
    address_detail         : {},
    billing_detail         : {},
    session_cookie_name    : 'user_sid',
    session_cookie_options : { path: '/', domain: '.20x200.com' },
    userdata_cookie_name   : 'userdata',
    insecure_domain        : 'https://www.20x200.com',
    secure_domain          : 'https://www.20x200.com',
    settings_uri           : '/membership/profile/settings/',
    login_uri              : '/membership/login/',
    logout_uri             : '/membership/logout/',
    static_login_uri       : '/membership/static/login/',
    static_logout_uri      : '/membership/static/logout/',
    registration_uri       : '/membership/registration/',
    checkout_cgi           : '/checkout/checkout.cgi',

    // login methods
    login: function(form, container) {
        var source = jQuery.data(document.body, 'source') || 'global';
        jQuery.ajax({ type: "POST",
                      url: "/membership/login/", 
                      data: jQuery(form).serialize(),
                      dataType: "json",
                      beforeSend: function() {
                          jQuery('#spinner').css({'visibility':'visible'});
                      },
                      success: function(data) {
                                   jQuery('#spinner').css({'visibility':'hidden'});
                                   if (data.status == "0") {
                                       _user.userdata = data;
                                       jQuery.cookie(_user.userdata_cookie_name, JSON.stringify(_user.userdata), _user.session_cookie_options);
                                       if (source == 'quasi-static-login') {
                                           window.location.replace(_user.secure_domain + _user.settings_uri);
                                       }
                                       else {
                                           jQuery.data(document.body, 'memberbox', jQuery('#member-box').html());
                                           var logstr = 'You are logged in as : <a href="/membership/profile/settings/">' + data.email + '</a>  |  ';
                                           logstr += '<span id="topbar-cart" style="display:none;"><a href="/cart/">Your Cart</a>  |  </span>';
                                           logstr += '<a href="#" onclick="_user.logout(\'#member-box\');">Log out</a>';
                                           jQuery('#member-box').html(logstr);
                                           jQuery(container).jqmHide();
                                       }
                                       if (source == 'checkout') {
                                           window.location.replace(_user.secure_domain + _user.checkout_cgi);
                                       }
                                   }
                                   else {
                                       jQuery('#login-errors').css({'visibility': 'visible','display' : 'block'});
                                       jQuery('#login-errors').html(data.message);
                                       jQuery('.jqmWindow').height(275);
                                   }
                               }
                     });
        return false;
    },

    // login methods
    secure_login: function(form, container) {
        var source = jQuery.data(document.body, 'source') || 'global';
        jQuery.ajax({ type: "GET",
                      url: _user.secure_domain + _user.login_uri + "?" + jQuery(form).serialize(),
                      dataType: "jsonp",
                      beforeSend: function() {
                          jQuery('#spinner').css({'visibility':'visible'});
                      },
                      success: function(data) {
                                   jQuery('#spinner').css({'visibility':'hidden'});
                                   if (data.status == "0") {
                                       _user.userdata = data;
                                       jQuery.cookie(_user.userdata_cookie_name, JSON.stringify(_user.userdata), _user.session_cookie_options);
                                       if (source == 'quasi-static-login') {
                                           window.location.replace(_user.secure_domain + _user.settings_uri);
                                       }
                                       else {
                                           jQuery.data(document.body, 'memberbox', jQuery('#member-box').html());
                                           var logstr = 'You are logged in as : <a href="' + _user.secure_domain + _user.settings_uri + '">' + data.email + '</a> | ';
                                           logstr += '<span id="topbar-cart" style="display:none;"><a href="/cart/">Your Cart</a>  |  </span>';
                                           logstr += '<a href="#" onclick="_user.logout(\'#member-box\');">Log out</a>';
                                           jQuery('#member-box').html(logstr);
                                           
                                           jQuery(container).jqmHide();
                                       }
                                       if (source == 'checkout') {
                                           window.location.replace(_user.secure_domain + _user.checkout_cgi);
                                       }
                                   }
                                   else {
                                       jQuery('#login-errors').css({'visibility': 'visible','display' : 'block'});
                                       jQuery('#login-errors').html(data.message);
                                       jQuery('.jqmWindow').height(275);
                                   }
                               }
                     });
        return false;
    },

    logged_in: function(div, source) {
        if (!source) { source = 'global' }
        var userdata = this.userdata;
        if (!userdata.status) {
            if (jQuery.cookie(_user.userdata_cookie_name)) {
                userdata = JSON.parse(jQuery.cookie(_user.userdata_cookie_name));
                this.userdata = userdata;
            }
        }
        if (userdata.status == "0" && this.has_valid_session()) {
            _kmq.push(['identify', userdata.email]);
            if (div) {
                if (source == 'checkout') {
                    var logstr = 'You are logged in as: <a href="' + _user.secure_domain + _user.settings_uri + '">' + userdata.email + '</a>&nbsp; | ';
                    logstr += '<a href="#" onclick="_user.logout(\'#member-box\');">Log out</a>';
                    jQuery(div).html(logstr);
	            jQuery('#login-link').attr('href', "https://www.20x200.com/checkout/checkout.cgi");
   //jQuery('#checkout-login-link').html('<a href="https://www.20x200.com/checkout/checkout.cgi" class="linkbutton" id="login-link">Go to Checkout</a>');
                }        
                else {
                    _user.memberbox = jQuery('#member-box');
                    var logstr = 'You are logged in as: <a href="' + _user.secure_domain + _user.settings_uri + '">' + userdata.email + '</a> | &nbsp;';
                    logstr += '<span id="topbar-cart" style="display:none;"><a href="/cart/">Your Cart</a>  |  </span>';
                    logstr += '<a href="#" onclick="_user.logout(\'#member-box\');">Log out</a>';
                    jQuery(div).html(logstr);
                }
            }
            else {
                return true;
            }
        }
        else {
            _kmq.push(['clearIdentity']);
            return false;
        }
    },

    logout: function(div) {
        var source = jQuery.data(document.body, 'source') || 'global';
        jQuery.ajax({ type: "POST",
                       url: _user.logout_uri,
                       dataType: "json",
                       complete: function(data) {
                                  jQuery.cookie(_user.session_cookie_name, null, _user.session_cookie_options);
                                  jQuery.cookie(_user.userdata_cookie_name, null, _user.session_cookie_options);
                                  setCookie(_user.session_cookie_name, '', '-30');
                                  setCookie(_user.userdata_cookie_name, '', '-30');
                                  document.cookie=_user.session_cookie_name+"=;path=/;domain=.20x200.com;expires=Thu, 01-Jan-1970 00:00:01 GMT";
                                  document.cookie=_user.userdata_cookie_name+"=;path=/;domain=.20x200.com;expires=Thu, 01-Jan-1970 00:00:01 GMT";

                                  if (source == 'membership') {
                                      window.location.replace(_user.secure_domain + _user.static_logout_uri);
                                  }
                                  else {
                                    var login_markup = '<a id="login-link" href="https://20x200.com/membership/static/login/">Log In</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a id="join-link" href="https://20x200.com/membership/static/join/">Create Your Account</a>';
                                    jQuery(div).html(login_markup, 'memberbox');
                                    var secure_domain = 'https://www.20x200.com';
                                    var domain = 'http://www.20x200.com';
                                    var return_url = jQuery.url.attr('relative');
                                    if (!return_url) {
                                        return_url = '/';
                                    }
                                    var link = secure_domain + '/membership/static/login/?return_url=' + domain + return_url;
                                    var jlink = secure_domain + '/membership/static/join/?return_url=' + domain + return_url;
                                    if (return_url.match(/^\/cart\//)) {
                                        link = secure_domain + '/membership/static/login/?return_url=' +  secure_domain + '/checkout/checkout.cgi';
                                        jlink = secure_domain + '/membership/static/join/?return_url=' + secure_domain + '/checkout/checkout.cgi';
                                    }

                                    jQuery('#login-link').attr('href', link);
                                    jQuery('#join-link').attr('href', jlink);

                                  }
                                }
                   });
        _kmq.push(['clearIdentity']);
        return false;
    },

    // registration methods
    registration: function(form, container) {
        var source = jQuery.data(document.body, 'source') || 'global';
        jQuery.ajax({ type: "POST",
                       url: "/membership/registration/", 
                       data: jQuery("#join-form").serialize(),
                       dataType: "json",
                       beforeSend: function() {
                           jQuery('#spinner').css({'visibility':'visible'});
                       },
                       success: function(data) {
                                    jQuery('#spinner').css({'visibility':'hidden'});
                                    if (data.status == "0") {
                                        _user.userdata = data;
                                        jQuery.cookie(_user.userdata_cookie_name, JSON.stringify(_user.userdata), _user.session_cookie_options);
                                        _user.logged_in('#member-box');
                                        if (source == 'checkout') {
                                            _user.logged_in('#checkout-login-link', 'checkout');
                                        }
                                        if (source == 'checkout-confirmation') {
                                            jQuery(container).html('<div id="registration-thanks"><div id="registration-email">Email <strong>' + _user.userdata.email + '</strong></div><p>Thanks for creating a 20x200 account!</p></div>');
                                        }
                                        else {
                                            jQuery(container).load("/includes/modal/registered.txt");
                                            jQuery('.jqmWindow').height(150);
                                        }
                                    }
                                    else {
                                        jQuery('#join-errors').css({'visibility': 'visible','display' : 'block'});
                                        jQuery('#join-errors').html(data.message);
                                        jQuery('.jqmWindow').height(300);
                                    }
                                }
                   });
        return false;
    },

    // registration methods
    secure_registration: function(form, container) {
        var source = jQuery.data(document.body, 'source') || 'global';
        jQuery.ajax({ type: "GET",
                       url: _user.secure_domain + _user.login_uri + "?" + jQuery("#join-form").serialize(),
                       dataType: "jsonp",
                       beforeSend: function() {
                           jQuery('#spinner').css({'visibility':'visible'});
                       },
                       success: function(data) {
                                    jQuery('#spinner').css({'visibility':'hidden'});
                                    if (data.status == "0") {
                                        _user.userdata = data;
                                        jQuery.cookie(_user.userdata_cookie_name, JSON.stringify(_user.userdata), _user.session_cookie_options);
                                        _user.logged_in('#member-box');
                                        if (source == 'checkout-confirmation') {
                                            jQuery(container).html('<div id="registration-thanks"><div id="registration-email">Email <strong>' + _user.userdata.email + '</strong></div><p>Thanks for creating a 20x200 account!</p></div>');

                                        }
                                        else {
                                            jQuery(container).load("/includes/modal/registered.txt");
                                        }
                                    }
                                    else {
                                        jQuery('#join-errors').css({'visibility': 'visible','display' : 'block'});
                                        jQuery('#join-errors').html(data.message);
                                        jQuery('.jqmWindow').height(275);
                                    }
                                }
                   });
        return false;
    },

    check_email: function(form) {
        jQuery.ajax({ type: "POST",
                       url: "/membership/check_email/",
                       data: ({ 'email' : jQuery("#email").val() }),
                       dataType: "json",
                       success: function(data) {
                                    if (data.status == "0") {
                                    }
                                    else {
                                        jQuery('#join-errors').css({'visibility': 'visible','display' : 'block'});
                                        jQuery('#join-errors').html(data.message);
                                        jQuery('.jqmWindow').height(250);
                                    }
                                }
                   
                   });
        return false;
    },

    // utility methods
    forgot_password: function(form, container) {
        jQuery.ajax({ type: "POST",
                      url: "/membership/forgot_password/",
                      data: jQuery(form).serialize(),
                      dataType: "json",
                       beforeSend: function() {
                           jQuery('#spinner').css({'visibility':'visible'});
                       },
                      success: function(data) {
                                   jQuery('#spinner').css({'visibility':'hidden'});
                                   if (data.status == "0") {
                                       jQuery(container).load("/includes/modal/forgot-password-sent.txt");
                                       jQuery('.jqmWindow').height(150);
                                   }
                                   else {
                                       jQuery('#forgot-password-errors').css({'visibility': 'visible','display' : 'block'});
                                       jQuery('#forgot-password-errors').html(data.message);
                                       jQuery('.jqmWindow').height(250);
                                   }
                               }
                     });
        return false;
    },

    // get address dropdown
    get_checkout_shipping_address_dropdown: function(document) {
        // populate shipping dropdown
        jQuery(document).ready(function(){
                    jQuery.getJSON("/membership/address/",{}, function(address){
                    var options = '<option></option>';
                    if (address.status == "0") {
                        var address_detail = address.address_detail;
                        _user.address_detail = address_detail;

                       // create the option box
                       for (var i = 0; i < address_detail.length; i++) {
                           options += '<option value="' + i
                                                        + '"';

                           if (address_detail[i].default_flag == 'Y') {
                               options += ' SELECTED ';
                           }

                           options += ">";

                           if (address_detail[i].default_flag == 'Y') {
                               options += '* ';
                           }

                           options +=                     address_detail[i].first_name
                                                        + ' ' 
                                                        + address_detail[i].last_name
                                                        + ' : ' 
                                                        + address_detail[i].address_line_1 
                                                        + ' ' 
                                                        + address_detail[i].address_line_2 
                                                        + ' ' 
                                                        + address_detail[i].address_line_3 
                                                        + ' ' 
                                                        + address_detail[i].city 
                                                        + ' ' 
                                                        + address_detail[i].state 
                                                        + ' ' 
                                                        + address_detail[i].zip 
                                                        + ' ' 
                                                        +'</option>';

                            // populate default address to form fields
                            if (address_detail[i].default_flag == 'Y') {
                                jQuery('#shipto_first_name').val(address_detail[i].first_name);
                                jQuery('#shipto_last_name').val(address_detail[i].last_name);
                                jQuery('#shipto_address').val(address_detail[i].address_line_1);
                                jQuery('#shipto_address2').val(address_detail[i].address_line_2);
                                jQuery('#shipto_company').val(address_detail[i].company);
                                jQuery('#shipto_city').val(address_detail[i].city);
                                jQuery('#shipto_state').val(address_detail[i].state);
                                jQuery('#shipto_zip').val(address_detail[i].zip);
                                jQuery('#shipto_country').val(address_detail[i].country);
                                jQuery('#phone').val(address_detail[i].telephone);
                            }
                        }
                        // add option data to div
                        jQuery("#shipto_addresses").html(options);
                    }
                    else {            
                        jQuery("#shipping-select").hide();
                        jQuery("#non-login-fields").show();
                        jQuery("#save_shipto_address").val(1);
                    }
            })
        });
        return false;
    },

    /////////////////////////////////////////////////////
    // common user/registration methods
    /////////////////////////////////////////////////////
    has_valid_session: function() {
        if (jQuery.cookie('logged_in')) {
        //if (getCookie(_user.session_cookie_name)) {
            return true 
        }
        else {
            return false;
        }
    }
};

///////////////////////////////////////
// modals
///////////////////////////////////////
var _modal = {

    login: function(div, source) {
    	jQuery(div).load("/includes/modal/login.txt", function(){
            jQuery('.jqmWindow').height(200);
            jQuery('#source').val(source);
            jQuery('#email').watermark('Email Address');
            jQuery('#email').click().css({ 'color' : '#000' });
            jQuery('#password-input').click().css({ 'color' : '#000' });
            jQuery('#password-input').watermark('Password');
    	});
    	return false;
    },

    join: function(div) {
        var source = jQuery.data(document.body, 'source') || 'global';
        jQuery(div).load("/includes/modal/registration.txt", function(){
            jQuery('.jqmWindow').height(240);
            jQuery('#email').watermark('Email Address', {useNative: false});
            jQuery('#password-input').watermark('Password', {useNative: false});
            jQuery('#password-confirm-input').watermark('Confirm Password', {useNative: false});
            jQuery('#email').click().css({ 'color' : '#000' });
            jQuery('#password-input').click().css({ 'color' : '#000' });
            jQuery('#password-confirm-input').click().css({ 'color' : '#000' });
            if (source == 'checkout') {
                jQuery('#header-join').html('<a href="#" onclick="_modal.login(jQuery(\'#member-lightbox\'));">Log in</a> if you already have a 20x200 account. Or, <a onclick="jQuery(\'#member-lightbox\').jqmHide();" href="/checkout/checkout.cgi">checkout as a guest</a>.');
            }
        });
        return false;
    },
    
    forgot_pass: function(div) {
        jQuery(div).load("/includes/modal/forgot-password.txt", function(){ 
            jQuery('.jqmWindow').height(190);
            jQuery('#email').watermark('Email Address');
            jQuery('#email').click().css({ 'color' : '#000' });
        });
        return false;
    }
};

if(!this.JSON){this.JSON={};}
(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});};}
if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}}());

