/**
 * Display tracking phone numbers, emails or images if a tracking source is 
 * specified in the url. A cookie saved the tracking source for subsequent 
 * visits - so that the tracking element will displayed until the cookie
 * expires.
 * 
 * --------------------------------------------------------------------------------
 * Requirements: jQuery & XML config file
 * 
 * Usage: 	This JavaScript will activate automatically on page load. The 
 * 			XML config file must be present. See 'ssm_source_config.xml'. 
 * 
 * 			To override default settings (e.g. change default cookie days):
 * 		  	$.fn.ssmsourcetrack( { 'cookie_days' : 90 } );
 * --------------------------------------------------------------------------------
 *
 * http://www.simplesmartads.com
 * 
 * Copyright (C) 2011 by Simple Smart Marketing, Inc. 
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * 
 */

(function($){
	
	var settings = {
			'url_param'			: 'ssmsource',				// the url parameter. e.g. site.com?ssm_source=<value>. if defined in the config file, the config file takes precedence.
			'base_path'			: null,						// will be updated in init
 			'config_file' 		: 'ssm_source_config',		// the config file, must be located in same dir as the js
			'cookie_prefix' 	: 'ssm',					// cookie prefix to ensure uniqueness
			'cookie_latest' 	: true,						// default: true. if true, the latest source is used (i.e. last visit with source defined)
			'cookie_days'		: 90						// number of days before cookie expires
	};	  
	
	var methods = {
			init 	: function(options) {
						if (options) $.extend(settings, options);
						setBasePath();
			},					
			
			update 	: function( ) { 
						updateFields(); 			
			}
						
	};
	
	$.fn.ssmsourcetrack = function( method ) {
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
					return methods.init.apply( this, arguments );
				} else {
					$.error( 'Method ' +  method + ' does not exist' );
				}    		
	};		
	
	// do the work of finding and updating all the fields in the DOM
	function updateFields() {
		
		$.get(settings.base_path + "/" + settings.config_file + '.xml', null, function(d) {
			
			// the default url source
			var url_param = $(d).find('sources').attr('url-param');
			if (url_param == null) {
				// assume default value
				url_param = settings.url_param;
			}
			
			// get the source from cookie or url. if a cookie already 
			// exists, the url gets preference and a new cookie is 
			// written
			var urlSource = ssm_getUrlParameter(url_param);
			
			var cookieName = settings.cookie_prefix + url_param;	
			var source = ssm_getCookie(cookieName);
			
			// cookie takes precedence over source in url 
			if (!isEmpty(source) && !isEmpty(urlSource)) {
				if (!settings.cookie_latest) {
					// url overrides the cookie
					ssm_setCookie(cookieName, urlSource, settings.cookie_days);
					source = urlSource;
				}
			} 
			
			// no cookie, source is set in url
			if (isEmpty(source) && !isEmpty(urlSource)) {
				ssm_setCookie(cookieName, urlSource, settings.cookie_days);
				source = urlSource;
			}
									
			$(d).find('source').each(function() {

				// get the source xml element
				var $xml = $(this);
		        var cls = $xml.attr('class');
		        var ref = '.' + cls;
		        
				var value = $xml.attr('trafficsource');
																				
				// if the provided source is in the config file, then
				// change the trackable value (tracking phone num, tracking email)
				if ((source != null) && (value == source)) {
					
			        var display_value = $xml.text();
			        var id_type = $xml.attr('type');
			        
			        if (id_type == null) {
				        // type not specified, so fill the inner html of the element	        	
			        	$(ref).html(display_value);	        	
			        } else if (id_type == "email") {
			        	// href mailto type. change the href value and display value
			        	$(ref).attr('href', 'mailto:' + display_value);
			        	$(ref).html(display_value);
			        } else if (id_type == "image") {
			        	// image type, change the image source
			        	$(ref).attr('src', display_value);
			        }
			        
				}
				
				// make sure the field is visible (set display to 'none' to avoid flicker when 
				// change occurs
				$(ref).show();
				
		      });	

		}, 'xml');			
	};
	
	function isEmpty(str) {
	    return (!str || 0 === str.length);
	}

	// get the parameter value from the url
	function ssm_getUrlParameter(name)
	{
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var reg = "[\\?&]" + name + "=([^&#]*)";
		var regex = new RegExp(reg);
		var results = regex.exec(window.location.href);
		if (results == null)
			return null;
		else
			return decodeURIComponent(results[1].replace(/\+/g, " "));
	};

	// set the cookie for subsequent visits
	function ssm_getCookie(name) {
		var nm = name + "=";
		var cs = document.cookie.split(';');
		for (var i=0; i < cs.length; i++) {
			var c = cs[i];
			while (c.charAt(0) == ' ') c = c.substring(1, c.length);
			if (c.indexOf(nm) == 0) return c.substring(nm.length, c.length);
		}
		return null;
	};

	// get the cookie, if it exists
	function ssm_setCookie(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days*86400000));
			var expires = "; expires=" + date.toGMTString();
		}
		else var expires = "";
		document.cookie = name + "=" + value + expires + "; path=/";
	};			
	
	function ssm_deleteCookie(name) {
		document.cookie = name + "=" + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";		
	}
	
	function setBasePath() {
		name = "jquery.ssmsourcetrack.js";
	    var scripts = document.getElementsByTagName('script');
	    for (var i = scripts.length - 1; i >= 0; --i) {
	      var src = scripts[i].src;
	      var l = src.length;
	      var length = name.length;
	      if (src.substr(l - length) == name) {
	        settings.base_path = src.substr(0, l - length);
	      }
	    }
	}
		
})( jQuery );

// on read, do the updates
$(document).ready(function() {
	$.fn.ssmsourcetrack('init');
	$.fn.ssmsourcetrack('update');
});


