var best_deal_domain = window.location.protocol + '//enews.businessreport.com';
var jQueryScriptOutputted = false;
var cookies = null;

function setTestCookie(callback){
	setCookie('testcookie','success',60,callback,false);
}

function getCookie(key,callback){
	uri = best_deal_domain + "/best_deal.php?class=cookie&action=getCookie&params[key]="+key+"&jsonp_callback=?";
	/*console.log("get cookie: " + uri);*/
	$.getJSON(uri,
	function(data){
		var value = data.value;
		if(jQuery.isFunction(callback)){
			/*console.log('passing value: ' + value);*/
			callback(value);
		}
	});	
}

function getCookies(){
	uri = best_deal_domain + "/best_deal.php?class=cookie&action=getCookies&jsonp_callback=?";
	/*console.log(uri);*/
	$.getJSON(uri,
	function(data){
		/*console.log(dump(data));*/
		cookies = data;
		if(typeof cookies.testcookie == 'undefined'){
			/* Plan B? */
		} else {
			if(typeof cookies.active != 'undefined' && cookies.active=='false'){
				//nothing active; do nothing
			} else {
				if(typeof cookies.seen != 'undefined' && cookies.seen=='true'){
					//do nothing
				} else {
					initFancybox();
				}
			}
		}
	});
}

var fancyboxOutputted = false;

function initFancybox() {	
    //if the jQuery object isn't available
    if (!(jQuery.isFunction(jQuery.fancybox))) {
        if (! fancyboxOutputted) {
            //only output the script once..
            fancyboxOutputted = true;
            
            //output the script (load it from google api)
            $('head').append("<link rel=\"stylesheet\" href=\"" + best_deal_domain + "/media/fancybox/jquery.fancybox-1.3.1.css\" type=\"text/css\" />");
			
			var headID = document.getElementsByTagName("head")[0];         
			var newScript = document.createElement('script');
			newScript.type = 'text/javascript';
			newScript.src = best_deal_domain + "/media/fancybox/jquery.fancybox-1.3.1.pack.js";
			headID.appendChild(newScript);     

            //'$('head').append("<scr" + "ipt type=\"text/javascript\" src=\"" + best_deal_domain + "/media/fancybox/jquery.fancybox-1.3.1.js\"></scr" + "ipt>");
        }
        setTimeout("initFancybox()", 50);
    } else {                   
        $(function() {  
			openPopup();
        });
    }  
}

function closedPopUp(){
	clearInterval(closeMePoll);
	var twenty_four_hours = 60*60*24;
	//var forty_eight_hours = 15;	/* 15 seconds for testing */
	setCookie('seen','true',twenty_four_hours,false);
}

var closeMePoll = 0;

function openPopup(){
	
	var uri = best_deal_domain + "/best_deal.php?class=renderer&action=getActive&jsonp_callback=?";
	$.getJSON(uri,
	function(data){

		var anchor = jQuery('<a />');
		anchor.attr('id','bestdeal_popup');
		anchor.html('test');
		anchor.addClass('iframe');
		anchor.css({'display':'none'})
		anchor.attr('href',best_deal_domain + '/best_deal.php');	
		$('body').append(anchor);
				
		$('#bestdeal_popup').fancybox({
			'autoScale':'false',
'scrolling' : 'no',
			'overlayShow' : 'true',
			'hideOnOverlayClick' : false,
			'hideOnContentClick' : false,
			'enableEscapeButton' : false,
			'showCloseButton' : true,
			'width':670,
			'height':data.window_height,
			'autoScale' : false,
			'type':'iframe',
			'onClosed' : closedPopUp,		
			'onCancel' : closedPopUp 		
		});
		
		$('#bestdeal_popup').click();		
		
		/* this cookie is used as a flag to determine whether window should be closed. 
		we set up polling for this after the window opens. */
		setCookie('closeme','false',600,null,true);

		closeMePoll = setInterval ("pollCloseMe()", 1000);
		
	});
}

function pollCloseMe ()
{
	getCookie("closeme",closeMe);
}

function closeMe(result){
	
	if(result=="true"){
		$('#fancybox-close').click();
		
		/* When the window is closed in this way, it indicates
		that the desired action was taken.  Therefore we leave
		the visitor alone for 10 years. */
		
		var ten_years = 60*60*24*365*10;
		setCookie('seen','true',ten_years,true);

	} else {
		return;
	}
	
}

function setCookie(key,value,time,callback,override){
	if(override) {
		var uri = best_deal_domain + "/best_deal.php?class=cookie&action=setCookie&params[override]=true&params[key]="+key+"&params[value]="+value+"&params[time]="+time+"&jsonp_callback=?";
	} else {
		var uri = best_deal_domain + "/best_deal.php?class=cookie&action=setCookie&params[key]="+key+"&params[value]="+value+"&params[time]="+time+"&jsonp_callback=?";
	}
	/*console.log('setCookie: ' + uri)*/
	$.getJSON(uri,
	function(data){
		if(jQuery.isFunction(callback)){
			callback();
		}
	});
}

/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function initJQuery() {
    //if the jQuery object isn't available
    if (typeof(jQuery) == 'undefined') {
        if (! jQueryScriptOutputted) {
            //only output the script once..
            jQueryScriptOutputted = true;
            
			var headID = document.getElementsByTagName("head")[0];         
			var newScript = document.createElement('script');
			newScript.type = 'text/javascript';
			newScript.src = best_deal_domain + "/media/js/jquery.js";
			headID.appendChild(newScript);     
        }
        setTimeout("initJQuery()", 50);
    } else {                   
        $(function() {  
			setTestCookie(getCookies);
        });
    }  
}

if(!window.console) {
  window.console = new function() {
    this.log = function(str) {};
    this.dir = function(str) {};
  };
}

initJQuery();
