function explode( delimiter, string, limit ) {
    // http://kevin.vanzonneveld.net
    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']
 
    var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}
function isset(varname){
  return(typeof(window[varname])!='undefined');
}
function ajaxRequest(){
var xmlHttp;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  return xmlHttp;
}
function getStatus(url, parseAt){
	var ajaxobject = ajaxRequest();
	if(!ajaxobject){
		//alert('AJAX not available');
	}else{
		docobjprogress = document.getElementById('ajaxProgressDiv');
		if(docobjprogress != null){
			docobjprogress.innerHTML = '<img src="/images/ajax_loader_d.gif" style="width:120px;height:15px;"/>';
		}
		ajaxobject.open("GET",url,true);
		ajaxobject.send(null);
		ajaxobject.onreadystatechange=function(){
			if(ajaxobject.readyState == 4){
				parseAndDisplay(ajaxobject.responseText, parseAt);
			}			
		}
	}
}
function parseAndDisplay(content, parseAt){
	contentarray = explode(parseAt, content);
	if(contentarray[1] != ''){
		docobj = document.getElementById('statusdiv');
		if(docobj != null){
			if(contentarray[1]){
				docobj.innerHTML = contentarray[1];
			}
		}
		docobj1 = document.getElementById('statusdivproblem');
		if(docobj1 != null){
			if(contentarray[1]){
				docobj1.innerHTML = contentarray[1];
			}
		}
		convertDate();
	}
}

function displayRank(rankdiv,url){
	var ajaxobject = ajaxRequest();
	
	if(!ajaxobject){
		//alert('AJAX not available');
	}else{
		docobjprogress = document.getElementById('ajaxProgressDivRank');
		if(docobjprogress != null){
			docobjprogress.innerHTML = '<img src="/images/ajax_loader_d.gif" style="width:120px;height:15px;"/>';
		}
		ajaxobject.open("GET",url,true);
		ajaxobject.send(null);
		ajaxobject.onreadystatechange=function(){
			if(ajaxobject.readyState == 4){
				parseAndDisplayRank(ajaxobject.responseText,rankdiv);
			}			
		}
	}
}

function parseAndDisplayRank(content,rankdiv){
	contentarray = explode('<rankcut>', content);
	docobj = document.getElementById(rankdiv);
	if(contentarray[1]){
		docobj.innerHTML = contentarray[1];
	}
}

function displayContestRank(rankdiv,url,countrycode){
	var ajaxobject = ajaxRequest();
	
	if(!ajaxobject){
		//alert('AJAX not available');
	}else{
		docobjprogress = document.getElementById('ajaxProgressDivRank');
		if(docobjprogress != null){
			docobjprogress.innerHTML = '<img src="/images/ajax_loader_d.gif" style="width:120px;height:15px;"/>';
		}
		ajaxobject.open("GET",url,true);
		ajaxobject.send(null);
		ajaxobject.onreadystatechange=function(){
			if(ajaxobject.readyState == 4){
				parseContestRank(ajaxobject.responseText,rankdiv,countrycode);
			}			
		}
	}
}

function parseContestRank(content,rankdiv,countrycode){
	contentarray = explode('<splithere>', content);
	docobj = document.getElementById(rankdiv);
	if(contentarray[1]){
		docobj.innerHTML = contentarray[1];
	}
	
	if(countrycode == "IN") {
		var replace_url = "/ranks/countries/IN/";
	}
	else if(countrycode == "US") {
		var replace_url = "/ranks/countries/US/";
	}
	else {
		var replace_url = "/ranks/";
	}
	
	//run a for loop for the following code
	$('.rank_pagi').each(function() {
		var callerFunc = $(this).attr("onclick");
		callerFunc = String(callerFunc);
		var funcName = callerFunc.slice((callerFunc.indexOf('{')+1), callerFunc.indexOf('}'));
		funcName = jQuery.trim(funcName);
		
		var newHref = funcName.slice(31);
	    newHref = newHref.slice(0,-2);
		
		var hrefStr = newHref.replace("/ranks/", replace_url);
		
		$(this).attr('onclick', '');
		$(this).click(function(){
			displayContestRank("rankdiv",hrefStr,countrycode);
		});
	});
}

//function to find the difference in dates in days,hours,minutes,sec
function date_diff(str_date, sys_date) {
	
	date1 = new Date();
	date2 = new Date();
	diff  = new Date();
	d	  = new Date();
	
	if(str_date.indexOf('-') != -1){
		str_date = str_date.replace(/-/g, '/');
		date1temp = new Date(Date.parse(str_date));
		date1 = date1temp.getTime();
		
		date2temp = new Date(Date.parse(sys_date));
		date2 = date2temp.getTime();
		
		// sets difference date to difference of first date and second date
		diff.setTime(Math.abs(date2 - date1));
		
		timediff = diff.getTime();
		
		weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
		timediff -= weeks * (1000 * 60 * 60 * 24 * 7);
		
		days = Math.floor(timediff / (1000 * 60 * 60 * 24)); 
		timediff -= days * (1000 * 60 * 60 * 24);
		
		hours = Math.floor(timediff / (1000 * 60 * 60)); 
		timediff -= hours * (1000 * 60 * 60);
		
		mins = Math.floor(timediff / (1000 * 60)); 
		timediff -= mins * (1000 * 60);
		
		secs = Math.floor(timediff / 1000); 
		timediff -= secs * 1000;
		
		var date_diff = '';
		
		if(mins == 0 && hours ==0 && days ==0 && weeks ==0) {
	    	date_diff = secs+' sec ago';
	    }
	    else if(hours == 0 && days ==0 && weeks ==0) {
	    	date_diff = mins+' min ago';
	    }
	    else if(days == 0 && weeks == 0) {
	    	date_diff = hours+' hours ago';
	    }
	    else if(days == 1 && weeks == 0) {
	    	date_diff = formatDate(date1temp, "hh:mm a")+' yesterday';
	    }
	    else {
	    	date_diff = formatDate(date1temp, "hh:mm a NNN dd");
	    }
	    
	    return date_diff;
	}	
}

function convertDate(){
	$('.status_dt').each(function(){
		var posted_date = jQuery.trim($(this).html());
		var new_date = date_diff(posted_date, sys_date);
		$(this).html(new_date);
	});
}

function formatTime(ts) {
  now = new Date(ts);
 
  localtime = new Date();
  hour = now.getHours();
  min = now.getMinutes();
  sec = now.getSeconds();
  
  if (min <= 9) {
	 min = "0" + min;
  }
  if (sec <= 9) {
	 sec = "0" + sec;
  }
  if (hour > 12) {
	 hour = hour - 12;
	 add = " PM";
  } else {
	 hour = hour;
	 add = " AM";
  }
  if (hour == 12) {
	 add = " PM";
  }
  if (hour == 00) {
	 hour = "12";
  }
	
  $('#server-time').html(((hour<=9) ? "0" + hour : hour) + ":" + min + ":" + sec + add);
  
  nextSec = (now.getTime() + 1000);
  
  setTimeout("formatTime("+nextSec+")", 1000);
}

function displaySolutionComments(url) {
	$('#commentProgressDiv img').css('display', '');
	$.ajax({
	  type: "GET",
	  url: url,
	  success: function showResult(msg) {
	  	$('#commentProgressDiv img').css('display', 'none');
	  	$('#commentdiv').html(msg);
	  }
	});
}

function submitPrize() {
	var prize = $('#prizes-value').val();
	var user = $('#prizes-uid').val();
	var post_data = "prize="+prize+"&user="+user;
	
	//check for the number of characters
	var minLen = 2; // min number of characters to comment
	var msg = "<font style='color: red;'>Value should have a minimum of 2 characters.</font>";
		
	if(prize.length < minLen)
	{
		
		$("#prizes-msg").html(msg).show();
		setTimeout('$("#prizes-msg").hide("slow")', 5000);
		return false;
	}
	
	//show a loader inpace of a submit button
	$('#prizes-submit').css('display', 'none');
	$('#loader-img').css('display', 'block');
	
	$.ajax({
	  type: "POST",
	  url: '/submit_prize.php',
	  data: post_data,
	  success: function(msg) {
	  	//hide the loader n show the submit button
	  	$('#loader-img').css('display', 'none');
	  	$('#prizes-submit').css('display', 'block');
	  	
	  	$('#prizes-value').val('');
	  	
	  	//show a success msg
	  	$("#prizes-msg").html(msg).show();
	  	
	  	setTimeout('$("#prizes-msg").hide("slow")', 5000);
	  }
	});
}

$(document).ready(function(){
	
	try{
		if(problem != null){
			//fine not an issue.
		}
	}catch(e){
		problem = null;
	}
	
	try{
		if(user != null){
			//fine not an issue.
	}
	}catch(e){
		user = null;
	}
	
	try{
		if(contest != null){
			//fine not an issue.
	}
	}catch(e){
		contest = null;
	}
	
	if(contest != null) {
		if(problem != null){
			//for contest specific problems recent activity
			getStatus('/'+contest+'/status/'+problem+'/', '<problemactivity>');
			
			if(callrank == 'y') {
				//for problem specific ranks
				displayRank("rankContentDiv", '/'+contest+'/ranks/'+problem+'/');
			}
		}
		else {
			if(user != null) {
				getStatus('/'+contest+'/status/'+user+'/', '<splithere>');
			}
			else {
				//for contest landing page
				getStatus('/'+contest+'/status/', '<splithere>');
			}
		}
	}
	else {
		if(problem != null){
			//for problem specific recent activity
			getStatus('/status/'+problem+'/', '<problemactivity>');
			
			if(callrank == 'y') {
				//for problem specific ranks
				displayRank("rankContentDiv", "/ranks/"+problem+"/");
			}
		}
		
		if(user != null) {
			//for user specific recent activity
			getStatus('/status/'+user+'/', '<useractivity>');
		}
		
		if(problem == null && user == null){
			if(isHome == 'n') {
				//for global recent activity
				getStatus('/status/', '<splithere>');
			}
			else {
				//for showing contest recent activity on the home page
				getStatus('/status/', '<homepage>');
			}
		}	
	}	
});
