/**
 * ==============================================================
 * File to contain all common javascript elements used in SBS 
 * sites but writing the queries using the jquery core library
 * ==============================================================
 */

/**
 * handles validation of comment forms
 * and submits the user-entered data
 * to a php script through ajax
 */
function makeComment(divName, useDivName) 
{
	var errorText = '';
	var formError = false;
	
	// we use this if we have multiple forms on one page
	// to make the fields unique to each form
	var prefix = '';
	if (useDivName) {
		prefix = divName + '_';
	}
	
	var site_id = document.getElementById(prefix + 'site_id').value;
	var article_id = document.getElementById(prefix + 'article_id').value;
	var article_url = document.getElementById(prefix + 'article_url').value;
	var article_type = document.getElementById(prefix + 'article_type').value;
	
	var userName = document.getElementById(prefix + 'txt_name').value;
	var userLocation = document.getElementById(prefix + 'txt_location').value;
	var userWebsite = document.getElementById(prefix + 'txt_website').value;
	var title = document.getElementById(prefix + 'txt_title').value;
	var comment = encodeURIComponent(document.getElementById(prefix + 'txt_comment').value);
	
	var private_key = document.getElementById(prefix + 'com_private_key').value;
	var public_key = document.getElementById(prefix + 'public_key').value;
	
	// do validation
	if(userName == "") {
		 errorText = errorText + "Please enter your name\n";
		 formError = true;
	}
	if(userLocation == "") {
		 errorText = errorText + "Please enter your suburb\n";
		 formError = true;
	}
	if ((userWebsite != '') && (!isUrl(userWebsite))) {
		 errorText = errorText + "Please enter a valid url\n";
		 formError = true;
	}
	if(title == "") {
		 errorText = errorText + "Please enter a title or subject\n";
		 formError = true;
	}
	if(comment == "") {
		 errorText = errorText + "Please enter your comment\n";
		 formError = true;
	}
	if(private_key == "") {
		 errorText = errorText + "Please enter the validation number\n";
		 formError = true;
	}

	if(formError) {
		window.alert(errorText);
		return;
	};
	
	// set up the post variables
	var data = encodeURI(
		'name=' + userName +
		'&location=' + userLocation +
		'&title=' + title +
		'&website=' + userWebsite +
		'&message=' + comment +
		'&public_key=' + public_key +
		'&com_private_key=' + private_key +
		'&site_id=' + site_id + 
		'&article_id=' + article_id + 
		'&article_url=' + article_url + 
		'&article_type=' + article_type
	);
	
	// send the url via ajax to a php script
	// and refresh content after success
	jQuery.ajax({
		type: 'POST',
		url: baseUrl + '/ajax/make-comment/',
		data: data,
		success: function(msg) {
			$('#' + divName).html(msg);
			//recordStats(siteUrl + 'submit_comment/article_id/' + article_id);
		}
	});
}

function getComments(article_id, article_type, page, pagelimit, divName, commentCount)
{
	var data = encodeURI(
		'article_id=' + article_id +
		'&article_type=' + article_type +
		'&page=' + page +
		'&pagelimit=' + pagelimit +
		'&commentCount=' + commentCount
	);
	
	// send the url via ajax to a php script
	// and refresh content after success
	jQuery.ajax({
		type: 'POST',
		url: baseUrl + '/ajax/get-comments/',
		data: data,
		success: function(msg) {
			$('#' + divName).html(msg);
			//recordStats(siteUrl + 'submit_comment/article_id/' + article_id);
		}
	});	
}

function getBloggerArticles(blogger_id, page, pagelimit, divName, articleCount)
{
	var data = encodeURI(
		'blogger_id=' + blogger_id +
		'&page=' + page +
		'&pagelimit=' + pagelimit +
		'&articleCount=' + articleCount
	);
	
	// send the url via ajax to a php script
	// and refresh content after success
	jQuery.ajax({
		type: 'POST',
		url: baseUrl + '/ajax/get-blogger-articles/',
		data: data,
		success: function(msg) {
			$('#' + divName).html(msg);
			//recordStats(siteUrl + 'submit_comment/article_id/' + article_id);
		}
	});	
}

/**
 * sets the agree/disagree vote for comments
 */
function makeCommentOpinion(comment_id, opinion, article_type) 
{
	/*
	switch (opinion) {
		case 0: divName = 'disagreeSpan' + comment_id; break;
		case 1: divName = 'agreeSpan' + comment_id; break;
	}
	*/
	// we're now replacing the entire opinion links area
	// and not just the individual agree/disagree links
	var divName = 'opinionDiv' + comment_id; 
	
	var data = encodeURI(
		'comment_id=' + comment_id +
		'&opinion=' + opinion +
		'&article_type=' + article_type
	);
	
	// send the url via ajax to a php script
	// and refresh content after success
	jQuery.ajax({
		type: 'POST',
		url: baseUrl + '/ajax/make-comment-opinion',
		data: data, 
		success: function(msg) {
			$('#' + divName).html(msg);
			//recordStats(siteUrl + 'submit_rating/epid/' + episodeID + '/commentid/' + commentID);
		}
	});
	
	

}

/**
 * limits the number of characters allowed to 
 * for a message in the comment form
 */
function limitText(limitField, limitCount, limitNum) 
{
	if (limitField.value.length > limitNum) {
		 limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}

function toggleFontSize(divName)
{
	var currentFontSize = $("p").css('font-size');
	var currentFontSizeNum = parseFloat(currentFontSize, 10);
	
	if ($(divName).hasClass("increaseFont")) {
		// decrease the font size
		var newFontSize = currentFontSizeNum - 2;
	} else {
		// increase the font by default
		var newFontSize = currentFontSizeNum + 2;
	}
	$("p").css('font-size', newFontSize);
	$(divName).toggleClass("increaseFont");
}

function increaseFontSize(divName)
{
	// Increase Font Size
	//$(".increaseFont").click(function(){
		var currentFontSize = $(divName).css('font-size');
		var currentFontSizeNum = parseFloat(currentFontSize, 10);
		//var newFontSize = currentFontSizeNum * 1.2;
		var newFontSize = currentFontSizeNum + 2;
		if (newFontSize <= 20) {
			$(divName).css('font-size', newFontSize);
		}
		//return false;
	//});
}

function decreaseFontSize(divName)
{
	// Decrease Font Size
	//$(".decreaseFont").click(function(){
		var currentFontSize = $(divName).css('font-size');
		var currentFontSizeNum = parseFloat(currentFontSize, 10);
		//console.log("current font size is " + currentFontSizeNum);
		//var newFontSize = currentFontSizeNum * 0.8;
		var newFontSize = currentFontSizeNum - 2;
		//console.log("new font size is " + newFontSize);
		if ( newFontSize >= 10 ) {
			$(divName).css('font-size', newFontSize);
		}
		//return false;
	//});
}

function resetFontSize()
{
	// Reset Font Size
	/*
	var originalFontSize = $('p').css('font-size');
	$(".resetFont").click(function(){
		$('html').css('font-size', originalFontSize);
	});
	*/
}

function printPage(print_type, article_id)
{
	var w = 740;
	var h = 600; 
	var LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	var TopPosition = (screen.height) ? (screen.height-h)/2 : 0;

	var printUrl = baseUrl + '/print/' + print_type + '/' + article_id;
	window.open(printUrl, 'print_view','width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',resizable=yes,scrollbars=yes');
}

function popupVideo(url) {
	window.open(url,'video','height=661,width=951,top=100,left=100,scrollbars=no,toolbars=no');
}

function popupGeneric(url, width, height) {
	window.open(url,'sbspopup','height=' + height + ',width=' + width + ',top=100,left=100,scrollbars=no,toolbars=no');
}

function popupGenScroll(url, width, height) {
	window.open(url,'sbspopup','height=' + height + ',width=' + width + ',top=100,left=100,scrollbars=yes,toolbars=no');
}

function recordStats(url)
{
	_rsEvent(url, '0');
}

function urldecode( str ) {
	// http://kevin.vanzonneveld.net
	// +   original by: Philip Peterson
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +      input by: AJ
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
	// *     example 1: urldecode('Kevin+van+Zonneveld%21');
	// *     returns 1: 'Kevin van Zonneveld!'
	// *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
	// *     returns 2: 'http://kevin.vanzonneveld.net/'
	// *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
	// *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
	
	var histogram = {}, histogram_r = {}, code = 0, str_tmp = [];
	var ret = str.toString();
	
	var replacer = function(search, replace, str) {
		var tmp_arr = [];
		tmp_arr = str.split(search);
		return tmp_arr.join(replace);
	};
	
	// The histogram is identical to the one in urlencode.
	histogram['!']   = '%21';
	histogram['%20'] = '+';
	
	for (replace in histogram) {
		search = histogram[replace]; // Switch order when decoding
		ret = replacer(search, replace, ret) // Custom replace. No regexing   
	}
	
	// End with decodeURIComponent, which most resembles PHP's encoding functions
	ret = decodeURIComponent(ret);
 
	return ret;
}

function isUrl(s) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return regexp.test(s);
}
