// Global Init File
var ieversion = 0; // Browser test - used in individual inits
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { // test for MSIE x.x;
	ieversion = new Number(RegExp.$1); // capture x.x portion and store as a number
}

var browser = {
    msie:document.all,
    msie6:(ieversion >= 6) ? true : false,
    msie7:(ieversion >= 7) ? true : false,
    msieShiv:(ieversion < 9) ? true : false
};

var env = {
    id:(function() {
	    var loc = location.href.toLowerCase();
	    var environment = (loc.indexOf('127.0.0.1') > -1 || loc.indexOf('localhost') > -1) ? 'local' : 
	    	              (loc.indexOf('dev-') > -1) ? 'dev' : 
	    	              (loc.indexOf('dprev') > -1) ? 'dprev' : 
	    	              (loc.indexOf('qa-') > -1) ? 'qa' : 
	    	              (loc.indexOf('qa2-') > -1) ? 'qa2' : 
		    	          (loc.indexOf('qprev') > -1) ? 'qprev' : 
			    	      (loc.indexOf('origin-stg-') > -1) ? 'origstg' : 
	    	              (loc.indexOf('stg-') > -1) ? 'stg' : 
	    	              (loc.indexOf('stag-') > -1) ? 'stag' : 
	    	              (loc.indexOf('sprev') > -1) ? 'sprev' : 
	    	              (loc.indexOf('pprev') > -1) ? 'pprev' : 
	    	              (loc.indexOf('orig') > -1) ? 'orig' : 
	    	              (loc.indexOf('beta') > -1) ? 'beta' : 'prod';
	    return (typeof environment == "undefined") ? 'prod' : environment;
    })(),
    isLocal:function() {
	    return ((this.id === 'local') ? true : false);
    },
    isDev:function() {
	    return ((this.id === 'dev') ? true : false);
    },
    isDprev:function() {
	    return ((this.id === 'dprev') ? true : false);
    },
    isQA:function() {
	    return ((this.id === 'qa') ? true : false);
    },
    isQA2:function() {
	    return ((this.id === 'qa2') ? true : false);
    },
    isQprev:function() {
	    return ((this.id === 'qprev') ? true : false);
    },
    isStg:function() {
	    return ((this.id === 'stg') ? true : false);
    },
    isStag:function() {
	    return ((this.id === 'stag') ? true : false);
    },
    isSprev:function() {
	    return ((this.id === 'sprev') ? true : false);
    },
    isProd:function() {
	    return ((this.id === 'prod') ? true : false);
    },
    isPprev:function() {
	    return ((this.id === 'pprev') ? true : false);
    },
    isPreview:function() {
	    return (((this.id).indexOf('prev') >= 0) ? true : false);
    },
    isOrigin:function() {
	    return (((this.id).indexOf('orig') >= 0) ? true : false);
    },
    isOriginStg:function() {
	    return (((this.id).indexOf('origstg') >= 0) ? true : false);
    },
    isBeta:function() {
	    return (((this.id).indexOf('beta') >= 0) ? true : false);
    },
    // make sure to also update search.form.submit in the code further in this file
    searchUrl:function() {
	    var url = (env.isLocal()) ? "" : 
 	              (env.isOriginStg()) ? "http://origin-stg-newsearch.travelchannel.com/travel/" : 
 	      		  (env.isOrigin()) ? "http://origin-search.travelchannel.com/travel/" : 
 	    	      (env.isBeta()) ? "http://origin-stg-newsearch.travelchannel.com/travel/" : 
	    	      (env.isDev()) ? "/travelchannel/Search_Result" : 
	    	      (env.isDprev()) ? "/travelchannel/Search_Result" : 
		    	  (env.isQA()) ? "http://qa-newsearch.travelchannel.com/travel/" : 
			      (env.isQA2()) ? "http://qa2-newsearch.travelchannel.com/travel/" : 
	    	      (env.isQprev()) ? "http://qa-newsearch.travelchannel.com/travel/" : 
	    	      (env.isStg()) ? "http://stg-newsearch.travelchannel.com/travel/" : 
	    	      (env.isStag()) ? "http://stg-newsearch.travelchannel.com/travel/" : 
	    	      (env.isSprev()) ? "/travelchannel/Search_Result" : 
	    	      (env.isPprev()) ? "/travelchannel/Search_Result" : "http://search.travelchannel.com/travel/";
	    return url;
    },
    autocompleteUrl:function() {
	    var url = (env.isLocal()) ? "http://dprevjboss1.travelchannel.com:8080/travel/" : 
	    	      (env.isBeta()) ? "http://beta-www.travelchannel.com/travel/" : 
	       	      (env.isOriginStg()) ? "http://beta-www.travelchannel.com/travel/" : 
	    	      (env.isDev()) ? "http://dprevjboss1.travelchannel.com:8080/travel/" : 
	    	      (env.isQA()) ? "http://sni-qa-www.travelchannel.com/travel/" : 
				  (env.isQA2()) ? "http://sni-qa2-www.travelchannel.com/travel/" : 
	    	      (env.isStg()) ? "http://sni-stg-www.travelchannel.com/travel/" : "http://www.travelchannel.com/travel/";
	    return url;
    },
	//testing URL for photogallery as it uses a different version of jQuery
	isPhotogallery:function() {	
		var loc = location.href.toLowerCase();
		return ( (loc.indexOf('/daily-escape') > -1) || (loc.indexOf('/photos/') > -1) || (loc.indexOf('/photo/')  > -1) || (loc.indexOf('slideshow')  > -1) ? true : false );
	},
	isVideo:function() {
    	var loc = location.href.toLowerCase();
    	return ( (loc.indexOf('/video') > -1) ? true : false );
	}		
};


var constant = {
	baseUrl:function() {
		var url = (env.isLocal()) ? "http://127.0.0.1:8080" : 
			      (env.isDev()) ? "http://sni-dev-www.travelchannel.com" : 
			      (env.isDprev()) ? "http://dprevjboss1.travelchannel.com:8080/travelchannel" : 
				  (env.isQA()) ? "http://sni-qa-www.travelchannel.com" : 
				  (env.isQA2()) ? "http://sni-qa2-www.travelchannel.com" : 
			      (env.isQprev()) ? "http://qprevjboss1.travelchannel.com:8080/travelchannel" : 
			      (env.isStg()) ? "http://sni-stg-www.travelchannel.com" : 
			      (env.isSprev()) ? "http://sprevjboss1.travelchannel.com:8080/travelchannel" : 
			      (env.isPprev()) ? "http://pprevjboss1.travelchannel.com:8080/travelchannel" : "http://www.travelchannel.com";
		return url;
	}
};

var init = {
    baseURI:{
        preload:"",
        css:"/static_files/assets/css/",
        js:"/static_files/assets/js/",
        json:"/static_files/assets/json/",
        links:"http://www.travelchannel.com/"
    },
    preload:{ // do not invoke after window.onload event
        js:function(url, doNotUseBaseURI) {
	        document.write('<scr' + 'ipt src="' + ((doNotUseBaseURI) ? '' : init.baseURI.js) + url + '"><\/script>');
        },
        css:function(url, media, doNotUseBaseURI) {
	        document.write('<link rel="stylesheet" type="text/css" href="' + ((doNotUseBaseURI) ? '' : init.baseURI.css) + url + '" ' + ((media) ? 'media="' + media + '"' : '') + '>');
        }
    },
    
    callback:null,
    initializer:function(callback) {
	    init.callback = callback; // store callback for later invocation
	    if (document.addEventListener) {
		    document.addEventListener('DOMContentLoaded', init.initialize, false);
	    }
	    (function() {
		    if (/loaded|complete/.test(document.readyState))
			    return init.initialize();
		    if (!init.initialize.done)
			    setTimeout(arguments.callee, 50);
	    })();
	    _prevOnload = window.onload;
	    window.onload = function() {
		    if (typeof _prevOnload === 'function')
			    _prevOnload();
		    init.initialize();
	    };
    },
    
    initialize:function() {
	    if (arguments.callee.done)
		    return;
	    arguments.callee.done = true;
	    // The DOM is ready
	    init.callback && init.callback(); // if there's a callback, invoke it
    }

};

// Pre-DOM: Load Global resource files/libraries that are NOT dependent on the DOM being ready
// Load Global Items
init.preload.css('/static_files/assets2/css/global.css', '',true);
init.preload.css('tcm-global.css');

if (env.isVideo()) {
    init.preload.js('lib/jquery/1.6.2.min.js');
} else if (env.isPhotogallery()) { 
	init.preload.js('sni/sni-jquery.js');
} else {
	init.preload.js('lib/jquery/1.3.1.min.js');
}
init.preload.js('lib/rf-forms.js');
init.preload.js('app/tc.js');
init.preload.js('lib/jquery/plugin/jquery.rating.js');
init.preload.js('lib/jquery/plugin/jquery.autocomplete.js');
init.preload.js('app/autocomplete_init.js');
init.preload.js('lib/flash/swfobject.js');
init.preload.js('lib/tcm-advertising.js'); 
init.preload.js('lib/log.js');
init.preload.js('/static_files/assets2/js/sni/sni-tc-cfg.js', true);
init.preload.js('/static_files/assets2/js/sni/sni-core.js', true);
init.preload.js('/static_files/assets2/js/sni/sni-tc.js', true);
init.preload.js('/static_files/assets2/js/jquery.tools.min.js', true);

if (browser.msieShiv) {
    init.preload.js('http://html5shiv.googlecode.com/svn/trunk/html5.js', true);
}

var search = {
	    form:"form[id='tcm-searchForm']",
	    submitSource:"submitButton",
	    configure:function() {
		    search.form.attr('method', 'post');
		    if (env.isPreview() || env.isLocal()) {
			    search.form.attr('action', env.searchUrl());
		    } else {
			    var url = env.searchUrl() + search.getQueryAsURL($("input[id='tc_search']").val()) + "/index.html";
			    search.form.attr('action', url);
		    }
		    return false;
	    },
	    getQueryAsURL:function(query) {
            // var query = $("input[id='tc_search']").val();
		    query = query.replace(/&/g, "and");// replace & with "and"
		    query = query.replace(/[^\w\']/g, " "); // replace non-url legal (i.e not letters, digits, ', etc.) characters with spaces
		    query = $.trim(query); // remove any pre or post spaces. Need to use jQuery trim, since it is not implemented in IE.
		    query = query.replace(/\s+/g, "-"); // replace space groups with "-"
		    query = query.toLowerCase();
		    return query;
	    },
	    reset:function() {
		    $("input[id='o']").attr('value', 0); // offset
		    $("input[id='p']").attr('value', 1); // page
		    $("input[id='d']").attr('value', ""); // dimension id
		    $("input[id='dn']").attr('value', ""); // dimension name
		    $("input[id='dt']").attr('value', ""); // dimension title (omniture only)
		    $("input[id='dr']").attr('value', ""); // dimension refinement label (omniture only)
		    $("input[id='da']").attr('value', ""); // dimension applied? (omniture only)
		    search.submitSource = 'submitButton'; // action taken to cause event
		    $("input[id='s']").attr('value', search.submitSource);
	    },
	    init:function() {
	        $("input[id='tc_search'], input[id='tc_search_footer']").focus(function(e) {
	            $(this).addClass('search-active');
	            if ($(this).val() == 'Search travelchannel.com') {
	                $(this).val('');
	            }
	        });
	        
	        $("input[id='tc_search'], input[id='tc_search_footer']").blur(function(e) {
	            $(this).removeClass('search-active');
	            if ($(this).val() == '') {
	                $(this).val('Search travelchannel.com');
	            }
	        });
	        
		    $("input[id='tc_search'], input[id='tc_search_footer']").change(function() {
			    search.reset();
		    });
		    
		    $("input[id='tc_search'], input[id='tc_search_footer']").keypress(function(e) {
			    search.reset();
			    if ($.browser.msie) {
				    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
					    this.blur();
					    this.focus();
				    }
			    }
		    });
		    
		    $("input[id='tc_search_submit'], input[id='tc_search_submit_footer']").keypress(function(e) {
			    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
				    e.preventDefault();
				    search.form.submit(this);
				    return false;
			    }
		    });
		    
		    $('#tcm-footerSearchForm').submit(function() {
		        var searchInput = $(this.q);
			    if (searchInput.val() == 'Search travelchannel.com' || searchInput.val() == '') {
			        searchInput.focus();
			        return false;
                } else {
                    $(this.q).val(search.getQueryAsURL($(this.q).val()));
                }
		    });
		    
		    search.form.submit(function() {
		        var searchInput = $(this.q);
			    if (searchInput.val() == 'Search travelchannel.com' || searchInput.val() == '') {
			        searchInput.focus();
			        return false;
			    }
			    if (($("input[name='q']").val()).length > 0) {
				    
				    if (search.submitSource === "submitButton") {
					    $("input[id='o']").attr('value', 0);
					    $("input[id='p']").attr('value', 1);
					    search.configure(search.form);
				    } else {
					    if (typeof searchTerm != "undefined" && searchTerm != null) {
						    if (searchTerm != $("input[name='q']").val()) {
							    $("input[name='q']").attr('value', searchTerm);
						    }
					    }
					    if (search.submitSource === 'pagination') {
						   // if (env.isProd() || env.isStg() || env.isQA() || env.isQprev() || env.isDev() || env.isLocal()) {
							    var url = env.searchUrl() + search.getQueryAsURL($("input[id='tc_search']").val()) + "/page-" + $("input[id='p']").val() + ".html";
							    search.form.attr('action', url);
							    search.form.attr('method', 'post');
						   // }
					    } else {
						    search.configure(search.form);
					    }
				    }
			    } else {
				    return false;
			    }
		    });
	    }
	};

// Utitlity function for Omniture Stats
function doOmniClickEvent(o) {
	var siteSection = "search";
	var moduleName = o.rel + ((o.rev.length > 0) ? ":" + o.rev : "");
	var moduleState = o.rev;
	
	// to insert h4 text if image is clicked
	var linkText = "";
	if ($(o).children("img").length > 0) {
		var imageTrack = "";
		
		// right rail - video, slideshow image click track
		if ($(o).parent(".item").length > 0) {
			imageTrack = $(o).parent(".item");  
			linkText = "image-" + imageTrack.find('h4 a').text();	
		}
		// spotlight - image click track
		if ($(o).parent(".topic-item").length > 0) {
			imageTrack = $(o).parent(".topic-item");  
			linkText = "image-" + imageTrack.find('h4 a').text();	
		}	
		// topic lead 1 - image click track
		if ($(o).parents(".lead-1").length > 0) {
			imageTrack = $(o).parents(".lead-1");
			linkText = "image-" + imageTrack.find('h2 a').text();	
		}					
		// topic lead 2 - image click track
		if ($(o).parents(".lead-2").length > 0) {
			imageTrack = $(o).parents(".lead-2");  
			linkText = "image-" + imageTrack.find('h2 a').text();	
		}			
		// topic lead 3 - image click track
		if ($(o).parents(".lead-3").length > 0) {
			imageTrack = $(o).parents(".lead-3");  
			linkText = "image-" + imageTrack.find('h2 a').text();
		}				

	} else { 
		// otherwise just use link tracking
		linkText = $(o).text();
	}
	
	var linkName = siteSection + ":" + moduleName + ":" + linkText; // search:top_videos:sams travel tips for asia
	var omniEvent = "none";
	// log.info("linkName=" + linkName);
	omniClickEvent(o, linkName);
	return true;
}

// Post-DOM: Load all js files/libraries that ARE dependent on the DOM being ready
function globalReady() { // init.initializer(ready); this is the callback function for when the dom is ready
	var $ = jQuery,
		pathname = window.location.pathname;
	search.form = $(search.form);
	search.init(); // Initialize the search features
	
	tc_autocomplete_init("#tc_search"); // Initialize the autosuggest feature

	if (typeof moduleReady == 'function') {
		moduleReady(); // Defined in individual init js
	}

	if (pathname.search(".quiz") < 0) {
		var cssLoc = location.protocol + "//" + location.host + "/static_files/assets2/css/stretchpages.css"
		$('<link rel="stylesheet" href="'+cssLoc+'" />').appendTo('head');
	}
	 if ($("#snd-sites")){
		 $("#snd-sites").tooltip({ position: "top center", relative: true});
	 }

     // fb init
     window.fbAsyncInit = function () {
         SNI.Social.FB.init();
         FB.Event.subscribe('edge.create', function(href, widget) {
         	try {
         		omniClickEvent(true, "Daily Escape:FB Like:" + mdManager.getParameter("title"), "event11");
         	} catch (e) {
         		//
         	}
         	SNI.Social.FB.checkUpdate(href);
         });
     };

     // load facebook JS
     (function() {
         var e = document.createElement('script'); e.async = true;
         e.src = document.location.protocol +
         '//connect.facebook.net/en_US/all.js#xfbml=1';
         document.getElementById('fb-root').appendChild(e);
     })();

}

init.initializer(globalReady);

//dummy function to prevent errors in QA2 debugging
function OAS_AD() {
    if (typeof(console) != 'undefined') {
        console.log("OLD AD CALLED!!");
    }
    return false;
}

