
// Make a post version of getJSON
$.postJSON = function(url, data, callback)
{
	$.post(url, data, callback, "json");
};

String.prototype.rot13 = function() {
    return this.replace(/[a-zA-Z]/g, function(c) {
        return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
    });
};

function initMenu()
{
	var nodes = document.getElementById("menu").getElementsByTagName("li");
	for (var i=0; i<nodes.length; i++)
	{
		nodes[i].onmouseover = function()
		{
			this.className += " hover";
		}
		nodes[i].onmouseout = function()
		{
			this.className = this.className.replace(" hover", "");
		}
	}
}
if (document.all && !window.opera) attachEvent("onload", initMenu);
function initPage()
{
	var n = document.getElementById("structure-menu");
	if (n)
	{
		var lis = n.getElementsByTagName("li");
		for (var i = 0; i < lis.length; i++)
		{
			if (lis[i].getElementsByTagName("ul").length)
			{
				if (lis[i].parentNode.id == "structure-menu")
				{
					var a = lis[i].getElementsByTagName("a").item(0);
					if (a)
					{
						a.onclick = function ()
						{
							var p = this.parentNode;
							if (p.className.indexOf("active") != -1)
								p.className = p.className.replace("active", "");
							else
								p.className += " active";
							return false;
						}
					}
				}
			}
		}
	}
}

// Adds of removes active class from classname, depending on state.
function toggleActive(classname)
{
	if (classname.indexOf("active") != -1)
		classname = classname.replace("active", "");
	else
		classname += " active";
		
	return classname;
}

// Clears the fields in the login form (or resets them)
function clearLoginField(fieldId)
{
	var field = document.getElementById(fieldId);
	if(fieldId == 'username')
	{
		if(field.value == 'email@address.com')
		{
			field.value = '';
		}
		else if(field.value == '')
		{
			field.value = 'email@address.com';
		}
	}
	else if(fieldId == 'password')
	{
		if(field.value == 'password')
		{
			field.value = '';
		}
		else if(field.value == '')
		{
			field.value = 'password';
		}
	}
}

// Get correct object to use fo ajax requests, depending on browser.
function getXMLHttpRequestObject()
{
	var xmlHttp=null;

	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	}
	catch(e)
	{
		// Internet Explorer
		try
		{
		    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e)
		{
		    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
    
	return xmlHttp;
}


var check = true;
function checkAll(form)
{
	var form = document.getElementById(form);
	
	// Loop the elemts of the form
	for(i=0; i<form.elements.length; i++)
	{
		// Check the checkboxes
		if(form.elements[i].type == 'checkbox')
			form.elements[i].checked = check;
	}
	
	// Switch for next click
	if(check)
		check = false;
	else
		check = true;
}


function doEnterLogin(e)
{
	var passwordField = document.getElementById('password');
	
	if(e.keyCode == "13")
	{
		 if(passwordField.value != 'password')
		 {
		 	passwordField.parentNode.parentNode.submit();
		 }
		 
		 return false;
	}

	return true;
}


if (window.addEventListener)
	window.addEventListener("load", initPage, false);
else if (window.attachEvent)
	window.attachEvent("onload", initPage);
	
	
// Formats date as: yyyy-mm-dd
function formatDate(date)
{
	var month = date.getMonth()+1;
	if (month < 10)
		month = "0" + month;
		
	var day = date.getDate();
	if (day < 10)
		day = "0" + day;

	var format = date.getFullYear() + "-" + month + "-" + day;
	return format;
}

// Formats time as: hh:mm:ss
function formatTime(date)
{
	var hour = date.getHours();
	if (hour < 10)
		hour = "0" + hour;
		
	var minutes = date.getMinutes();
	if (minutes < 10)
		minutes = "0" + minutes;
		
	var seconds = date.getSeconds();
	if (seconds < 10)
		seconds = "0" + seconds;
	
	 var format = hour + ":" + minutes + ":" + seconds;
	 return format;
}

var newTextForAttentionFlash = '';
function attentionFlash(id, newText)
{
	$("#" + id).fadeOut(500, flashCallback);
	newTextForAttentionFlash = newText;
}

function flashCallback()
{
	$(this).html(newTextForAttentionFlash);
	$(this).css("color","#ff0000");
	$(this).fadeIn(300).animate( { color: '#505050' }, 800);
}

function isValidUrl(url)
{
	// TODO: Opera refuse to pass anything with our regexp
	if(navigator.userAgent.search(/opera/i) != -1)
		return true;

	var regexstr = /^(http(s)?:\/\/)?([a-z0-9-_\.:@]+\.)*(([a-z0-9-])+(\.)([a-z0-9]){1,4})+(\:\d+)?(\/[a-z0-9-_\.%&\?\/=\+\[\]~\|:#,;@\$]*)*$/i;
	var regexp = new RegExp();
	regexp.compile(regexstr);

	if(regexp.test(url.toLowerCase()))
		return true;
		
	return false;
}

function toggleFlagPopup(id)
{
	var isIE = navigator.userAgent.search(/msie/i) != -1 ? true : false;
	var popup = $('#' + id);
	
	if(popup.is(':visible'))
	{
		if(isIE)
			popup.hide();
		else
			popup.fadeOut(500);
	}
	else
	{
		if(isIE)
			popup.show();
		else
			popup.fadeIn(200);
	}
	
}

function displayUpgradeNote(element)
{
    var divID = 'upgrade-popup-' + Math.round(Math.random() * 10000000000000000);
    
    var html = '<div id="' + divID + '" style="z-index: 10000; position:absolute; width: 200px; height: 100px; background-color: #ffffff; border: 2px solid #7DAC2A">' +
               '<span style="margin: 20px; width: 80%; float: left;">To use this feature, you must <a href="/user.php">upgrade your account</a>.</span>' +
               '<a style="float: right; margin-right: 10px;" class="btn" href="#">' +
               '<span style="line-height: 18px;" onclick="$(\'#' + divID +  '\').remove();return false;">Close</span>' +
               '</a>' +
               '</div>';
    
    $(element).after(html);
}

function disableField(disableID, afterID)
{
    if(!(disableID instanceof Array))
    {
        disableID = new Array(disableID);
    }

    var clickerHtml = '<span><a href="#" onclick="displayUpgradeNote(this);return false;">?</a></span>';
    
    for(var i=0; i < disableID.length; i++)
    {
        var disableElement = $('#' + disableID[i]);
        var afterElement = (afterID == undefined) ? $('#' + disableID[i]) : $('#' + afterID);
        
        disableElement.attr("disabled", "disabled");
        if(disableElement.attr("type") == "radio")
            disableElement.addClass("disabledRadio")
        else
            disableElement.addClass("disabledField");
    }
    afterElement.after(clickerHtml);
}

function recorderBack()
{
	if (history.length <= 1)
		self.close();
	else
		history.back();
}

function changePassword()
{
	var box = $('#passwordBox');
	if (box.is(":hidden"))
		box.slideDown('slow');
	else
		box.slideUp('slow');
}

function puffRotator()
{
	var params = '?page='+ window.location.pathname;
	
	if(puffRotatorCategory != "")
	    params += '&category='+ puffRotatorCategory;

	// Set the default title to "IN FOCUS" and clear the extra content
	$('#puff-title').html('IN FOCUS');
	$('#puff-extra').html('');
	$.get('/ajax/puff.php' + params, {}, function(data){
		$(".puffRotator").html(data);
		setTimeout('puffRotator();', 1000 * 90);
	});
}

function freetestListUpdater()
{
	$.get('/ajax/freetest-list.php', {}, freetestListUpdaterCallback);
}

function freetestListUpdaterCallback(data)
{
	$("#freetest-list-holder").html(data);
	setTimeout("freetestListUpdater();", 1000 * 55);
}

function freeanalysisListUpdater()
{
	$.get('/ajax/freeanalysis-list.php', {}, freeanalysisListUpdaterCallback);
}

function freeanalysisListUpdaterCallback(data)
{
	$("#freeanalysis-list-holder").html(data);
	setTimeout("freeanalysisListUpdater();", 1000 * 55);
}

function roundForAxis(value)
{
	value = Math.ceil(value);
	var i=0;
	while(value > 10)
	{
		value = value / 10;
		i++;
	}
	value = Math.ceil(value);
	while(i > 0)
	{
		value = value * 10;
		i--;
	}
	
	return value;
}

function isValidEmail(email)
{
	// TODO: implement me!
	return true;
}

// String helpers //

function getShorter(string, chars)
{
	if (isNaN(chars))
		chars = 80;
    
    if (string.length > chars)
        return string.substr(0, chars-3) + '...';
        
    return string;
}

function hex2dec(hex)
{
    var result = 0;
    var values = new Array();
    values['0'] = 0;
    values['1'] = 1;
    values['2'] = 2;
    values['3'] = 3;
    values['4'] = 4;
    values['5'] = 5;
    values['6'] = 6;
    values['7'] = 7;
    values['8'] = 8;
    values['9'] = 9;
    values['a'] = 10;
    values['b'] = 11;
    values['c'] = 12;
    values['d'] = 13;
    values['e'] = 14;
    values['f'] = 15;
    
    var count = hex.length;
    
    hex = hex.toLowerCase();
    
    for (i = 1; i < count; i++)
    {
       result += Math.pow(16,count-i) * values[hex.charAt(i-1)];
    }
    
    result += values[hex.charAt(count-1)];
    
    return result;
}

// Use whatever order you want :)
function startsWith(str1, str2)
{
	if (str1 == undefined || str2 == undefined)
	   return false;
	
	var length1 = str1.length;
	var length2 = str2.length;
	
    if (length1 > length2)	
    	if (str1.substr(0,length2) == str2)
    	   return true;
    else
    	if (str2.substr(0,length1) == str1)
           return true;
    
    return false;
}

var refreshTimer = 5*60000;
var refreshRate = 60000;
var lastUserActivity = 0;
if (window.attachEvent)
	window.attachEvent('onload', setUserActivity)
else if (window.addEventListener)
	window.addEventListener('load', setUserActivity, false);
	
function setUserActivity()
{
	var d = new Date();
	lastUserActivity = d.getTime();
}


function updatePage()
{
	var d = new Date();
	var time = d.getTime();

	if ((time - lastUserActivity) >= refreshTimer)
	{
		if (document.location.href.indexOf('queuetest.php') == -1 &&
			document.location.href.indexOf('edittest.php') == -1 &&
			document.location.href.indexOf('pageanalyzer.php') == -1 &&
			document.location.href.indexOf('complete.php') == -1)
			document.location.href = document.location.href;
	}	
	setTimeout("updatePage();",  refreshRate);	
}
setTimeout("updatePage();",  refreshRate);

var transparentImage = "transparent.gif";

function fixTrans()
{
	if (typeof document.body.style.maxHeight == 'undefined') {
		var imgs = document.getElementsByTagName("img");
		for (i = 0; i < imgs.length; i++)
		{	
			if (imgs[i].src.indexOf(".png") != -1)
			{
				imgs[i].parentNode.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgs[i].src + "',sizingMethod='crop')";
				imgs[i].parentNode.style.display = "inline-block";
				imgs[i].style.visibility = "hidden";
			}
		}
	}
}

function runBotCheck(id)
{
	var old = $('#' + id).val();
	var modified = old.rot13();
	$('#' + id).val(modified);
}

function getNewVerificationImage(id)
{
    var now = new Date();
    $('#' + id).attr('src', '/captcha.php?' + now.getTime());
}

if (document.all && !window.opera)
	attachEvent("onload", fixTrans);
