/* 
 * Set cookie on user's machine when they first visit our site via a vanity url.
 * Sets the cookie for 30 days.
 *
 * Using http://code.google.com/p/cookies/wiki/Documentation
 * 
 *
 */

if(typeof(RTR_COOKIES) === 'undefined') {
    var RTR_COOKIES = {
    };
}

//Object to actually manage the cookies.
RTR_COOKIES = {
    setCookie: function( currPage ){
        var rtrCookieName = 'rtrSignupSource'; //Name of cookie to set.
        var registerSource = currPage; //from page to get current page.
        var isNotSignup = ( registerSource !== 'signup'); //makes sure that we are not tracking the default signup page nor overwriting our cookie with the signup page.
        var cookieResult = $.cookies.test(); //makes sure that the user can actually accept cookies.
        //var cookieResult = testCookies(); //makes sure that the user can actually accept cookies.
       
        var expireDate = new Date();
        expireDate.setDate( expireDate.getDate()+30); //set expiration date of cookie 30 days into the future.
        var cookieDomain = location.host;
    
        var rtrOptions = { //Cookie Options
            domain: cookieDomain,
            expiresAt: expireDate
        }; 
        var formName = $( 'form#user-register' );
        var referralField = $( 'input#edit-profile-referral');
       
        if( cookieResult && isNotSignup ) {
     
            $.cookies.set( rtrCookieName,registerSource,rtrOptions); //set new cookie
        }
        
        //on submit, grabs the signup value from the cookie and injects it back into the registration form.
        formName.submit( function(){ 
            
            var cookieValue = $.cookies.get( rtrCookieName );
            if( cookieValue ) {
                referralField.val(cookieValue);
            }
        }
            
        );
    },

    google_analytics: function(){
    },

    // profileReferralCookie sets a cookie to be passed into the profile_referral form field at registration.  
    // This captures data based on query sting info from participating websites.  
    //profileReferralCookie accepts 3 arguments as properties of an associative array: 
    //cookie_name : the name of the cookie
    //value : a value to over-ride the default value. NOTE: if there is already a cookie, it may not be over-written.  
    //test_string : a test string which is used to check whether the page's URL contains a query string.
    profileReferralCookie : function(options){
        var prOptions = {
        cookie_name : 'rtr_profile_referral', 
        value : 'undefined',  
        test_string : '&campaign=' 
        }; 
        var options = $.extend(prOptions, options);  
        var cookie_value; // to be determined... via extreme string manipulation. 
        var cookie_options = { //Cookie Options
            domain: location.host,
            path : '/', 
            expires: 100 
        }
        //Note that pathname is used to get cookies from URLs with no question marks. For example landing page URLs use only and ampresand to differentiate 
	var pathname = document.location.pathname; 
	var search = document.location.search; 
	//The following 6 variables make up the cookie_value
	var landing_page; 
	var hero; 
	var campaign; 
	var call_action; 
	var offer_code; 
	var keywords; 
        //The following variables are tests for the cookie
        var is_not_signup = (!pathname.indexOf('signup')); //makes sure that we are not tracking the default signup page nor overwriting our cookie with the signup page.
        !pathname.indexOf('signup') > -1 ? is_not_signup = true : is_not_signup = false;
        var cookies_enabled = RTR_COOKIES.testCookies(); //makes sure that the user can actually accept cookies.
        // If the header contains node id, pass node id in as cookie. otherwise, get metadata expected on landing pages. 
        if (is_node_id())
        {
            get_node_meta(is_node_id()); 
        }
        else 
        {
            get_lp_meta(); 
        }
        // if the programmer has not passed in a cookie value to over write the default, make the cookie value equal to the following. 
        if (options.value == 'undefined')
        {
            cookie_value = landing_page +'-'+ hero +'-'+ campaign +'-'+ call_action +'-'+ offer_code +'-'+ keywords; 
            options.value = cookie_value; 
        }
        //Finally... if all of the following conditions are met, write the cookie. 
        //if( cookies_enabled && is_not_signup && !$.cookie(options.cookie_name) && options.value != 'signup') // If cookies are enabled, you are not on the signup page, and the cookie does not exist
        if(conditions_true())
        {
            $.cookie(options.cookie_name, options.value, cookie_options); //set new cookie 
        }
        // Checks all conditions that must evalueate to true to write the cookie.
        function conditions_true()
        {
            var return_val = false; 
            if (pathname.indexOf(options.test_string) <= -1 && search.indexOf('?source=') <= -1)
            {
                return_val =  false; 
                return return_val; 
            }
            else if (!cookies_enabled) 
            {
                return_val =  false; 
                return return_val; 
            }
            else if (!is_not_signup) 
            {
                return_val =  false; 
                return return_val; 
            }
            else if (!$.cookie(options.cookie_name)) 
            {
                return_val = true; 
            }
            return return_val; 
        }
        function is_node_id()
        {
            var return_val; 
            if ($('meta[name="nid"]').length > -1)
            {
                if ($('meta[name="nid"]').attr('content') == '')
                {
                    return_val = 'nodeid_null'; 
                }
                else 
                {
                    return_val = $('meta[name="nid"]').attr('content');
                }
            }
            else 
            {
                return_val = false; 
            }
            return return_val; 
        }
        // This function gets meta data for pages with node id, ie not custom landing pages. 
        function get_node_meta(node_id)
        {
            landing_page = 'lr'; 
            if (pathname.indexOf('my/hearts') > -1)
            {
                pathname.split('my/hearts')[1] != undefined ? hero = 'mh' + pathname.split('my/hearts')[1].split('/')[1] : hero = 'mh'; // Set the hero to my (for my hearts) and the uid of the my hearts page.
            }
            else if (node_id != 'nodeid_null')
            {
                hero = node_id; // Set the hero to the node id. - This should be the majority of cases...
            }
            else
            {
                hero = pathname.split('&')[0].split('/').join('_') //Set hero to page path 
            }
            // Notice that the following statement looks for ?source= , and not &source= (and not &campaign=)
            search.split('?source=')[1] != undefined ? campaign = search.split('?source=')[1].split('&')[0] : campaign= ''; //Set campaign
            search.split('&CTA=')[1] != undefined ? call_action= search.split('&CTA=')[1].split('&')[0] : call_action= ''; //Set call_action
            search.split('&Off=')[1] != undefined ? offer_code = search.split('&Off=')[1].split('&')[0] : offer_code = ''; //Set offer_code
            search.split('&KY=')[1] != undefined ? keywords = search.split('&KY=')[1].split('&')[0] : keywords = ''; //Set keywords
        }
        // This function gets meta for traditional landing pages - usually PPC lp
        function get_lp_meta()
        {
            // On the landing pages, if the #edit-profile-referral field has tracking data, bypass regular function and create cookie with this value. 
            if ($('#edit-profile-referral').length > 0) 
            {
                options.value = $('#edit-profile-referral').val(); 
                /*campaign = ''; 
                call_action = ''; 
                offer_code = ''; 
                keywords = ''; */
            }
            else 
            {
                landing_page = 'lp'; 
                //hero = $('#image_carousel').find('img').attr('src').split('/')[len-1]; 
                var len = pathname.split('&')[0].split('/').length; 
                pathname.split('&')[0].split('/') != undefined ? hero = pathname.split('&')[0].split('/')[len-1] : hero = ''; 
                pathname.split('&campaign=')[1] != undefined ? campaign = pathname.split('&campaign=')[1].split('&')[0] : campaign= ''; //Set campaign
                pathname.split('&CTA=')[1] != undefined ? call_action= pathname.split('&CTA=')[1].split('&')[0] : call_action= ''; //Set call_action
                pathname.split('&Off=')[1] != undefined ? offer_code = pathname.split('&Off=')[1].split('&')[0] : offer_code = ''; //Set offer_code
                pathname.split('&KY=')[1] != undefined ? keywords = pathname.split('&KY=')[1].split('&')[0] : keywords = ''; //Set keywords
                 
            }
        }
    },

    //setProfileReferral accepts two arguments, the selector for the form field to be set, and the name of the cookie 
    setProfileReferral : function(form_field, cookie_name){
        // Set the value of the form field to the cookie name
        val = $.cookie(cookie_name);  
        $(form_field).val(val); 
    }, 

    testCookies : function(){
        //Tests to see if the user has cookies enabled.  If not... well they suck at cookies. 
    	//Uses the jqery.cookie.js plugin, $.cookie.  Not to be confused with $.cookies plugin ;(
    	$.cookie('rtr_test_user_cookies', 'on'); 
    	var isOn; 
    	if ($.cookie('rtr_test_user_cookies'))
    	{
    		isOn = true; 
    	        $.cookie('rtr_test_user_cookies', null); 
    	}
    	else
    	{
    		isOn = false; 
    	}
    	return isOn; 
    }

// End RTR_COOKIES
}

$(document).ready(function(){

	//sets cookie automatically on document.ready
	//RTR_COOKIES.profileReferralCookie(); 

        // on the home page, set the profile referral field to cookie it available. 
        /*if ($.cookie('rtr_profile_referral'))
        {
            RTR_COOKIES.setProfileReferral('#user-register-front input[name="profile_referral"]', 'rtr_profile_referral'); 
	}*/

//End document.ready functions
}); 





