/*
 * jQuery JSON Plugin
 * version: 1.0 (2008-04-17)
 *
 * This document is licensed as free software under the terms of the
 * MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 * Brantley Harris technically wrote this plugin, but it is based somewhat
 * on the JSON.org website's http://www.json.org/json2.js, which proclaims:
 * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
 * I uphold.  I really just cleaned it up.
 *
 * It is also based heavily on MochiKit's serializeJSON, which is 
 * copywrited 2005 by Bob Ippolito.
 */
 
(function($) {   
    function toIntegersAtLease(n) 
    // Format integers to have at least two digits.
    {    
        return n < 10 ? '0' + n : n;
    }

    Date.prototype.toJSON = function(date)
    // Yes, it polutes the Date namespace, but we'll allow it here, as
    // it's damned usefull.
    {
        return date.getUTCFullYear()   + '-' +
             toIntegersAtLease(date.getUTCMonth() + 1) + '-' +
             toIntegersAtLease(date.getUTCDate());
    };

    var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
    var meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        }
        
    $.quoteString = function(string)
    // Places quotes around a string, inteligently.
    // If the string contains no control characters, no quote characters, and no
    // backslash characters, then we can safely slap some quotes around it.
    // Otherwise we must also replace the offending characters with safe escape
    // sequences.
    {
        if (escapeable.test(string))
        {
            return '"' + string.replace(escapeable, function (a) 
            {
                var c = meta[a];
                if (typeof c === 'string') {
                    return c;
                }
                c = a.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"'
        }
        return '"' + string + '"';
    }
    
    $.toJSON = function(o)
    {
        var type = typeof(o);
        
        if (type == "undefined")
            return "undefined";
        else if (type == "number" || type == "boolean")
            return o + "";
        else if (o === null)
            return "null";
        
        // Is it a string?
        if (type == "string") 
        {
            return $.quoteString(o);
        }
        
        // Does it have a .toJSON function?
        if (type == "object" && typeof o.toJSON == "function") 
            return o.toJSON();
        
        // Is it an array?
        if (type != "function" && typeof(o.length) == "number") 
        {
            var ret = [];
            for (var i = 0; i < o.length; i++) {
                ret.push( $.toJSON(o[i]) );
            }
            return "[" + ret.join(", ") + "]";
        }
        
        // If it's a function, we have to warn somebody!
        if (type == "function") {
            throw new TypeError("Unable to convert object of type 'function' to json.");
        }
        
        // It's probably an object, then.
        ret = [];
        for (var k in o) {
            var name;
            var type = typeof(k);
            
            if (type == "number")
                name = '"' + k + '"';
            else if (type == "string")
                name = $.quoteString(k);
            else
                continue;  //skip non-string or number keys
            
            val = $.toJSON(o[k]);
            if (typeof(val) != "string") {
                // skip non-serializable values
                continue;
            }
            
            ret.push(name + ": " + val);
        }
        return "{" + ret.join(", ") + "}";
    }
    
    $.evalJSON = function(src)
    // Evals JSON that we know to be safe.
    {
        return eval("(" + src + ")");
    }
    
    $.secureEvalJSON = function(src)
    // Evals JSON in a way that is *more* secure.
    {
        var filtered = src;
        filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
        filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
        filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
        
        if (/^[\],:{}\s]*$/.test(filtered))
            return eval("(" + src + ")");
        else
            throw new SyntaxError("Error parsing JSON, source is not valid.");
    }
})(jQuery);

var FSPrompt;
var FSPromptSettings = {};
var promptWindow = null;
var surveyURL = '';
var popOver = false;

function getPromptInfo(){
	return {
		"surveyURL": surveyURL,
		"message": FSPromptSettings['messages']['standby'],
		"style": FSPromptSettings['style']['standby']
	};
}

//Sets the cookie for this prompt
function setPromptCookie(hours,value){
	if (hours){
		if(hours == -1){
			hours = 200000;
		}
		var date = new Date();
		date.setTime(date.getTime()+(hours*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}else{
		var expires = "";
	} 
	document.cookie = 'FSPrompt-'+ FSPromptCookieID + "="+value+expires+"; path=/";
	return true;
}

//Get the value of a cookie
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


//Tells the child window that the parent has changed pages
function promptUnload(){
	try {
		if (readCookie('FSPrompt-' + FSPromptCookieID) == 'waiting') {
			setPromptCookie(-1, 'complete');
		}
		promptWindow.parentUnload();
	}catch(e){
		return false;
	}
}

function setUnload(){
	//Preserve any existing onUnload function
	currentUnload = window.onunload;
	if (typeof window.onunload != 'function') {
		window.onunload = promptUnload;
	}
	else {
		window.onunload = function(){
			currentUnload();
			promptUnload();
		};
	}
}

//Gets the handle to the popup window
function setPopup(wind){
	promptWindow = wind;
	setPromptCookie(24,'waiting');
	setUnload();
}


//Close an open prompt
function closePrompt(accept){
	if (accept == 0) {
		setPromptCookie(-1,'deny');
	}else {
		setPromptCookie(24,'waiting');
	}
	if (FSPromptSettings['settings']['dm'] == 'fade') {
		$(FSPrompt).fadeOut('slow', function(){
			$(this).remove();
		})
	}
	else {
		$(FSPrompt).remove();
	}
}
//Click one of the options
function promptClick(answer){
	if (answer == 1){
		if(window.FSStandbyUrl === undefined){
			promptWindow = window.open(surveyURL,'FSPromptWindow','width=1000,height=600,left=100,top=100,scrollbars=1');	
			setPromptCookie(-1,'completed');
		}else{
			promptWindow = window.open(FSStandbyUrl,'FSPromptWindow','width=1000,height=600,left=100,top=100,scrollbars=1');
			promptWindow.PromptStyle = FSPromptSettings['style']['standby'];
			promptWindow.surveyURL = surveyURL;
			promptWindow.PromptMessage = FSPromptSettings['messages']['standby'];
		}
		if (!popOver) {
			promptWindow.blur();
			window.focus();
		}			
		closePrompt(true);
	}else{
		closePrompt(false);
	}
}

//Create the prompt object
function createPrompt(prompt){
	var main = $('<div></div>').attr('id','FSpopup').css({
				'position': 'fixed',
				'top': '0px',
				'left': '0px',
				'z-index': 2147483642,
				'width': '100%',
				'height': '100%',
				'font-family': 'Trebuchet MS,Verdana,Helvetica,Arial,Sans-serif',
				'display': 'none'
		});
	main.append(
		$('<div></div>').css({
				'position': 'absolute',
				'top': '0px',
				'left': '0px',
				'z-index': 2147483645,
				'background-color': prompt['style']['sb']['color'],
				'opacity': parseFloat(prompt['style']['sb']['opacity']/100),
				'filter': 'alpha(opacity='+parseInt(prompt['style']['sb']['opacity'])+')',
				'width': '100%',
				'height': '100%',
				'display': ((prompt['style']['sb']['enabled']) ? 'block' : 'none')					
		}).addClass('FSIEFixedFix').html('&nbsp;')
	);
	
	if(prompt['style']['overall']['height'] == "auto" || prompt['style']['overall']['height'] == 'inherit'){
		var height = "auto";
	}else{
		var height = prompt['style']['overall']['height'] + 'px';
	}
	
	var inner = $('<div></div>').css({
					'position': 'relative',
					'top': '200px',
					'z-index': 2147483646,
					'margin': '0 auto',
					'overflow': 'hidden',								
					'background-color': prompt['style']['overall']['bg'],
					'width': prompt['style']['overall']['width'] + 'px',
					'height': height,
					'border': prompt['style']['overall']['border']['width'] + 'px ' + prompt['style']['overall']['border']['style']	+ ' ' + prompt['style']['overall']['border']['color']		
				});
	
	$(inner).append(
		$('<div></div>').css({
			'background-color': prompt['style']['header']['bg'],
			'font-weight': 700,
			'color': prompt['style']['header']['fc'],
			'font-size': prompt['style']['header']['fs'],
			'text-align': prompt['style']['header']['align'],
			'padding': '3px'
		}).html(prompt['messages']['header'])
	);
	
	$(inner).append(
		$('<p></p>').css({
			'color': prompt['style']['message']['fc'],
			'font-size': prompt['style']['message']['fs'],
			'text-align': prompt['style']['message']['align'],
			'padding': '0px 8px',
			'line-height': 'normal',
			'margin-top': '6px',
			'margin-bottom': '20px'
		}).html(prompt['messages']['message'])
	);
	
	var buttons = $('<div></div>').css({
		'text-align': 'center',
		'margin-bottom': '15px'
	})
	.addClass('clearfix')
	.append(
		$('<div></div>').css({
			'width': '50%',
			'float': 'left'
		}).append(
			$('<a></a>').css({
				'display': 'block',
				'position': 'relative',
				'margin': '0 auto',
				'width': prompt['style']['buttons']['width'] + '%',
				'border': prompt['style']['buttons']['border']['width'] + 'px ' + prompt['style']['buttons']['border']['style']	+ ' ' + prompt['style']['buttons']['border']['color'],
				'padding': '1px 3px 2px 3px',
				'background-color': prompt['style']['buttons']['bg'],
				'font-weight': 'bold',
				'color': prompt['style']['buttons']['fc'],
				'font-size': prompt['style']['buttons']['fs'],
				'text-decoration': 'none'
			}).attr('href','javascript:promptClick(1);').html(prompt['messages']['yes'])
		)
	)
	.append(
		$('<div></div>').css({
			'width': '50%',
			'float': 'left'
		}).append(
			$('<a></a>').css({
				'display': 'block',
				'position': 'relative',
				'margin': '0 auto',
				'width': prompt['style']['buttons']['width'] + '%',
				'border': prompt['style']['buttons']['border']['width'] + 'px ' + prompt['style']['buttons']['border']['style']	+ ' ' + prompt['style']['buttons']['border']['color'],
				'padding': '1px 3px 2px 3px',
				'background-color': prompt['style']['buttons']['bg'],
				'font-weight': 'bold',
				'color': prompt['style']['buttons']['fc'],
				'font-size': prompt['style']['buttons']['fs'],
				'text-decoration': 'none'
			}).attr('href','javascript:promptClick(0);').html(prompt['messages']['no'])
		)					
	);
	
	$(main).append($(inner).append($(buttons)));
	main.repositionPrompt = function(){
		inner.css({
			top: ($(window).height() - inner.height()) / 2 + 'px'
		});
	};
	$(window).resize(main.repositionPrompt);
	return main;
}

//Show the prompt
function showPrompt(mode){
	if (mode == 'fade') {
		$(FSPrompt).fadeIn("slow");
	}
	else {
		$(FSPrompt).show();
	}
	$(window).resize();
}

$(function(){
  if (typeof(FSPromptID) == 'undefined' || typeof(FSPromptCookieID) == 'undefined') {
    return;
  }
	cookieVal = readCookie('FSPrompt-'+ FSPromptCookieID);
	if (cookieVal != 'deny' && cookieVal != 'complete' && cookieVal != null) {
		setUnload();
	}
	if(cookieVal == null){
		$.getJSON(statusURL+ '?prompt_id=' + FSPromptID + '&callback=?', function(data){
			if(data['success'] == true){
				if(data['deny'] == true){
					setPromptCookie(data['postpone'],'deny');
					return false;
				}
				if(data.show == true){	
					FSPromptSettings = data['prompt'];
					if (FSPromptSettings['settings']['popOver'] == true){
						popOver = true;
					}			
					FSPrompt = createPrompt(FSPromptSettings);
					surveyURL = data['surveyURL'];
					$('body').append(FSPrompt);
					setTimeout('showPrompt("'+FSPromptSettings['settings']['dm']+'")',(FSPromptSettings['settings']['delay']*1000));
					setUnload();
				}
			}
		});	
	}	
});

