/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
// http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
$.extend({
  getUrlVars: function(url){
  	//window.location.href
  	if(!url) url = window.location.href;
  	
    var vars = [], hash;
    var hashes = url.slice(url.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];
  },
  
  setReferrerCookie: function(){
    if (!$.cookie("referrerCookie")) {
  	  $.cookie("referrerCookie", document.referrer);
    }
  },
	
	extractSearchTerms: function(){
		referrer_url = $.cookie("referrerCookie");
		var search_engine_vars = [];
		request_vars = ($.getUrlVars(referrer_url));
	
		// google
		if (referrer_url.search(/www\.google/) != -1){
			search_engine_vars['term'] = unescape(request_vars['q']).replace(/\+/g, " ");
			search_engine_vars['engine'] = 'google';
		
		// yahoo
		} else if (referrer_url.search(/search\.yahoo/) != -1){
			search_engine_vars['term'] = unescape(request_vars['p']).replace(/\+/g, " ");
			search_engine_vars['engine'] = 'yahoo';
		
		// bing
		} else if (referrer_url.search(/bing\./) != -1){
			search_engine_vars['term'] = unescape(request_vars['q']).replace(/\+/g, " ");
			search_engine_vars['engine'] = 'bing';

		// ask
		} else if (referrer_url.search(/ask\.com/) != -1){
			search_engine_vars['term'] = unescape(request_vars['q']).replace(/\+/g, " ");
			search_engine_vars['engine'] = 'ask';

		// aol
		} else if (referrer_url.search(/aol\.com/) != -1){
			search_engine_vars['term'] = unescape(request_vars['q']).replace(/\+/g, " ");
			search_engine_vars['engine'] = 'aol';
		
		// not a search engine
		} else {
			// do nothing
		}
		return search_engine_vars;
	},

	// 
	// sets the affiliate cookies
	// and redirects back to the original page without the request parameters
	//
	setAffiliateCookie: function(){
		var referrer_vars = [];
		request_vars = $.getUrlVars();
		if(request_vars['affiliate_id'] && (!$.cookie("affiliate_type"))){
			
  	  $.cookie("affiliate_id", request_vars['affiliate_id']);
  	  $.cookie("affiliate_link_id", request_vars['affiliate_link_id']);
			
			var referrer_url = $.cookie("referrerCookie")
		  $.ajax({
		    type: "GET",
		    url: "/affiliates/log_visit",
				data: { 
					affiliate_id: request_vars['affiliate_id'],
					affiliate_link_id: request_vars['affiliate_link_id'], 
					referrer: referrer_url 
				},
				async: false,
		    dataType: 'script'
		  });

			url = window.location.href.split("?");		
			window.location = url[0];
		}
	},
	
  addHiddenFields: function(field_name){
	  if(!field_name || field_name == '') field_name = 'lead';
	  search_engine_vars = $.extractSearchTerms();
		referrer_url = $.cookie("referrerCookie");
		
		form = $('form');
		
		// add in the referrer_url
		if(referrer_url) form.append('<input type="hidden" value="' + referrer_url + '" name="' + field_name + '[referrer]">');
		
		if($.cookie("affiliate_id")) form.append('<input type="hidden" value="' + $.cookie("affiliate_id") + '" name="' + field_name + '[affiliate_id]">')
		if($.cookie("affiliate_link_id")) form.append('<input type="hidden" value="' + $.cookie("affiliate_link_id") + '" name="' + field_name + '[affiliate_link_id]">')
		
		// if they came from a search engine
		if(search_engine_vars['term']){
			form.append('<input type="hidden" value="' + search_engine_vars['term'] + '" name="' + field_name + '[search_term]">')
			form.append('<input type="hidden" value="' + search_engine_vars['engine'] + '" name="' + field_name + '[search_engine]">');
		}
		
  }

});
