try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

/**
 * static object that handles page logic
 */
var Logic = function($){
	/**
	 * private methods and variables
	 */
	var priv = {
		debug	: (resources.debugmode == 'true'),		//enables/disables the error logging
		debugSeverity : 10,	//level of error logging
		console	: $("<ul>").addClass("debug-console"),
				
		initConsole	: function(){
			//if the console has not yet been added to the document, do so now
			if(!priv.console.parentNode){
				$("body").append(priv.console);
			} 
		},
		
		bindEvents : function(){
		    // make whole price blocks clickable
		    $('#content div.general-info-price').bind('click', function(){
		        location.href = $(this).find('a').attr('href');
		    });
		    
		    // bind userinfo clicks
            $("#content a.user_popup").each(function (i) {
                $(this).jHelperTip({
		            trigger: "click",
		            source: "ajax",
		            type: "GET", 
		            url: resources.path_prefix+'/utilpages/getcontrol.ashx',
		            data: this.rel+'&loadControl='+encodeURI('~/controls/accommodation/userinfo.ascx'),
		            loadingImg: resources.path_prefix+'/images/ajax-loader.gif',
		            loadingText: 'laden...',
		            autoClose: false, 
		            opacity: 1.0
	            });
            });
            //hide the popups on body click
            $("body").bind("click",
		        function(evt){
		            $('div.user-profile-popup[dir!=ltr]').hide();
		        }
		    );
		    
		    if($('td.hotspot').length){
		        $('td.hotspot').bind('click', function(){
		            location.href = $(this).find('a').attr('href');
		        });
		    }
		    
		    $("#ribbon-tag div").bind("click",
		        function(evt){
		            Lightbox.Show(585, 'pSendReaction');
		            return false;
		        }
		    );
        }		
	};
	
	/**
	 * public methods
	 */
	return {		
		/**
		 * initializes the page logic
		 * to be called on $(document).ready
		 */
		OnReady	: function(){
		    $.browser.msie6 = ($.browser.msie && typeof(XMLHttpRequest) == "undefined" && /MSIE 6\.0/i.test(window.navigator.userAgent) && !/MSIE 7\.0/i.test(window.navigator.userAgent) && !/MSIE 8\.0/i.test(window.navigator.userAgent)); 
		    Logic.writeDebug("IE6? : " + $.browser.msie6);
			//add trim method to the string object
			String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g,"");}
			String.prototype.stripTags = function() {return this.replace(/<(.|\n)*?>/g, "");}
			String.format = function()
            {
                if( arguments.length == 0 )
                    return null;

                var str = arguments[0];
                for(var i=1;i<arguments.length;i++)
                {
                    var re = new RegExp('\\{' + (i-1) + '\\}','gm');
                    str = str.replace(re, arguments[i]);
                }

                return str;
            }            
            
//            if(typeof(Home) != "undefined"){
//                Home.OnReady();
//            }
			if(typeof(Profile) != "undefined"){
                Profile.OnReady();
			}
            if(typeof(Destination) != "undefined"){
                Destination.OnReady();
			}
			if(typeof(travelers) != "undefined"){
			    travelers.OnReady();
			}
            if(typeof(Accommodation) != "undefined"){
                Accommodation.OnReady();
            }		
			if(typeof(Prices) != "undefined"){
                Prices.OnReady();
			}
			if(typeof(Static) != "undefined"){
			    Static.OnReady();
			}
			if(typeof(Formsubmit) != "undefined"){
			    Formsubmit.OnReady();
			}
			if(typeof(Search) != "undefined"){
                Search.OnReady();
			}
			if(typeof(Home) != "undefined"){
                Home.OnReady();
			}
			if(typeof(bookingLogic) != "undefined"){
                bookingLogic.OnReady();
			}
			if(typeof(personalItems) != "undefined"){
			    personalItems.Load('alreadyviewed');
			    personalItems.Load('favorites');
//				personalItems.ShowItemLinks();
			}
			
			priv.bindEvents();
			
			//firefox select all "issue"
            if($.browser.mozilla){
                $("body").bind("mousedown", function(evt){
                    if(evt.target.tagName == "BODY"){
                        return false;
                    }
                });
            }
			
			if(!priv.debug){
			    $("span.error").hide();
			}

			$("#content .watisdit").jHelperTip({
			    trigger: "hover",
			    source: "attribute",
			    attrName: "rel",
			    autoClose: true
			}); 
		},
				
		OnResize	: function(){
		    //Lightbox.OnResize();
		},
		
		getJsParams : function (javascriptfile){
            var params = new Object();

            javascriptfile = javascriptfile + '?';
            var tags = document.getElementsByTagName('script');
            for (var n = 0; n < tags.length; n++)
            {
                var startIndex = tags[n].src.indexOf(javascriptfile);
                if(startIndex != -1){
                   var urlparams = tags[n].src.substring(javascriptfile.length+startIndex);
                   var params = urlparams.split('&');
                   for(var i = 0;i<params.length;i++){
                     var param = params[i].split('=');
                     if(param[1] != null && param[1] != ''){
                        params[param[0]] = param[1];
                     }
                   }
                }
            }
            
            return params;
        },

        getURLParam : function (strParameterName, strURL)
        {
            if(strURL == null || typeof(strURL) == "undefined")
                strURL = location.href;
            
            var splitChar = '?';
            if ( strURL.indexOf (splitChar) == -1 )
                splitChar = '#';
                
            if ( strURL.indexOf (splitChar) > 0 )
            {
                var strParameters = strURL.split (splitChar) [1].split ("&");
                for ( i = 0; i < strParameters.length; i++ )
                {
                    if ( strParameters [i].indexOf ("=") > 0 )
                    {
                        var strParameterValue = strParameters [ i ].split ("=");
                        if ( strParameterValue [0] == strParameterName )
                            return strParameterValue [1].split('#')[0];
                    }
                }
            }
            return "";
        },
        
        removeURLParam : function (strURL, strParameterName)
        {                            
            var newUrl = '';
            var strParameters = strURL.split ("&");
            for ( i = 0; i < strParameters.length; i++ )
            {
                if (strParameters[i].indexOf("=") > 0 && strParameters[i].indexOf(strParameterName+"=") == -1)
                {
                    var strParameterValue = strParameters [ i ].split ("=");
                    newUrl += newUrl == '' ? strParameterValue[0] + '=' +strParameterValue[1] : '&'+strParameterValue[0] + '=' +strParameterValue[1];
                }
            }
            
            return newUrl;
        },
        
        getPageName : function () {
            var sPath = window.location.pathname;
            return sPath.substring(sPath.lastIndexOf('/') + 1);
        },
        
        repositionMarker : function(id,top)
        {

        },
        
        redirect : function(url)
        {

            return false;
        },
        		
		/**
		 * handles the writing of debug messages
		 * @param {String} msg
		 * @param {Int} severity: 0 info, 1 warning, 2 error, 3 critical
		 */
		writeDebug	: function(msg, severity){
			if(typeof(severity) == "undefined"){
				severity = 0;
			}
			
			if(priv.debug && severity <= priv.debugSeverity){
				//check whether debug console exists
				if(typeof(console) != "undefined" && console.log){
					console.log(msg);
				}
				//if no debug console exists: create debug div
				else {
					priv.initConsole();
					$(priv.console).append(
						$("<li>").html(msg)
					);
				}
			}
		}

	}
}(jQuery);

var Timer = function(){
    var priv = {
        startTime : new Date(),
        endTime   : null
    };
        
    return {
        Start : function(){
            priv.startTime = new Date();
        },
        
        Stop : function(){
            priv.endTime = new Date();
            return (priv.endTime - priv.startTime);
        },
        
        ShowIntermediate : function(){
            var intermediateTime = new Date();
            return (intermediateTime - priv.startTime); 
        },
        
        GetStartTime : function(){
            return priv.startTime;
        }
    };
};

/**
 * Initiate onload methods and functions
 */
$(document).ready(
    

	function(){
	    if($('.hdnShowMsg').val() != '')
	    {
	        Lightbox.Show(400, "popup_content_" + $('.hdnShowMsg').val());
	    }
	
	    var TotalOnreadyTime = new Timer();
		Logic.OnReady();
		Logic.writeDebug("script time was: " + (TotalOnreadyTime.Stop()) + "ms ", -1);
        
        $('.marker span.lnk').bind('click', function() {
            location.replace($(this).attr('lnk'));
        });
        
        $('.marker label').bind('click', function() {
            location.replace($(this).attr('lnk'));
        });
        
        $('#inp-search').bind('keypress', function(e) {
            if(e.keyCode == 13) {
                Search.doTextSearch()
            }
        });
        
	}
);

/**
 * Bind resize eventes
 */
$(window).bind('resize', 
	function(){
		Logic.OnResize();
});
