/* General functions */

// Open a new window
function NewWindow(mypage, myname, w, h, scroll) {
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',scrollbars=' + scroll + ',resizable,toolbar=yes'
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

// Crossbrowser event attacher
function addEvent(obj, evType, fn) {
	if (obj.addEventListener)
	{
		obj.addEventListener(evType, fn, false);
		return true;
	}
	else if (obj.attachEvent)
	{
		var r = obj.attachEvent("on" + evType, fn);
		return r;
	}
	else
	{
		return false;
	}
}

/* Shop */

function PriceFormatter(decimalsDef, decimalSepDef, groupSepDef, groupSizeDef, patternDef, currencyDef, negativePatternDef) {
	this.decimals = parseInt(decimalsDef);
	this.decimalSeparator = decimalSepDef;
	this.groupSeparator = groupSepDef;
	this.groupSize = parseInt(groupSizeDef);
	this.pattern = parseInt(patternDef);
	this.negativePattern = negativePatternDef;
	this.currency = currencyDef;
}

function PriceToDouble(price_string, formatter, isEmptyNeed) {
	var result;
	if (isEmptyNeed && price_string == "") {
		result = price_string;
	} else {
		var s = new String(price_string);
		var groupSeparator = formatter.groupSeparator.replace(",","\\,").replace(".","\\.");
		var decimalSeparator = formatter.decimalSeparator.replace(",","\\,").replace(".","\\.");
		if(decimalSeparator == "") { decimalSeparator = "."; }

		re = new RegExp(groupSeparator, "g");
		s = s.replace(re, "");

		re = /\ /g;
		s = s.replace(re, "");

		re = new RegExp(decimalSeparator, "g");
		s = s.replace(re, ".");

		var fnum = parseFloat(s);
		if (isNaN(fnum) || s == "") {
			if (isEmptyNeed) {
				result = "";
			} else {
				result = 0;
			}
		} else {
			result = Math.round(fnum * Math.pow(10, formatter.decimals)) / Math.pow(10, formatter.decimals);
		}
		return result;
	}
}

function StringToDouble(source_string, formatter, isEmptyNeed) {
	var s = new String(source_string);
	var groupSeparator = formatter.groupSeparator.replace(",","\\,").replace(".","\\.");
	var decimalSeparator = formatter.decimalSeparator.replace(",","\\,").replace(".","\\.");
	if(decimalSeparator == "") { decimalSeparator = "."; }

	re = new RegExp(groupSeparator, "g");
	s = s.replace(re, "");

	re = /\ /g;
	s = s.replace(re, "");

	re = new RegExp(decimalSeparator, "g");
	s = s.replace(re, ".");

	var fnum = parseFloat(s);
	var result;
	if (isNaN(fnum) || s == "")
	{
		if (isEmptyNeed)
		{
			result = "";
		} else
		{
			result = 0;
		}
	} else
	{
		result = fnum;
	}
	return result;
}

// Converts a double value to a price string 
// with groups, decimal separator and format pattern configured in the "formatter"
function DoubleToPrice(price_double, formatter, isCurrencyNeed) {
	var roundedPrice = Math.round(price_double * Math.pow(10, formatter.decimals)) / Math.pow(10, formatter.decimals);

	var s = new String(isNaN(roundedPrice) ? "" : roundedPrice);
	var decimalEndPos = (price_double < 0 ? 1 : 0);

	if (s != "")
	{
		re = new RegExp("\\.", "g");
		s = s.replace(re, formatter.decimalSeparator);

		var separatorPos = s.indexOf(formatter.decimalSeparator, 0);
		var missingDecimals = 0;
		if (separatorPos < 0)
		{
			separatorPos = s.length;
			missingDecimals = formatter.decimals;
			s += formatter.decimalSeparator;
		} else
		{
			missingDecimals = formatter.decimals - (s.length - separatorPos - 1);
		}

		s += Array(missingDecimals + 1).join('0');

		// insert group separators
		separatorPos -= formatter.groupSize;
		while (separatorPos > decimalEndPos)
		{
			s = s.substring(0, separatorPos) + formatter.groupSeparator + s.substring(separatorPos, s.length);
			separatorPos -= formatter.groupSize;
		}
	}

	// Add currency in the configured pattern
	if (isCurrencyNeed) { 
		if(price_double >= 0)
		{
			// Positive patterns
			switch(formatter.pattern) {
				case 0: // $n
					s = formatter.currency + s; 
					break;
				case 1: // n$
					s = s + formatter.currency; 
					break;
				case 2: // $ n
					s = formatter.currency + ' ' + s; 
					break;
				case 3: // n $
					s = s + ' ' + formatter.currency; 
					break;
				default:
					s = s + formatter.currency;
					break;
			}
		} else {
			// Negative patterns
			sAbs = s.replace(/^-/, "");
			switch(formatter.negativePattern) {
				case 1: // -$n
					s = '-' + formatter.currency + sAbs;
					break;
				case 2: // $-n
					s = formatter.currency + s; 
					break;
				case 5: // -n$
					s = s + formatter.currency; 
					break;
				case 8: // -n $
					s = s + ' ' + formatter.currency; 
					break;
				case 9: // -$ n
					s = '-' + formatter.currency + ' ' + sAbs;
					break;
				case 12: // $ -n
					s = formatter.currency + ' ' + s; 
					break;
				default:
					s = s + formatter.currency;
					break;
			}
		}
	}
	return s;
}

function DoubleToString(source_double, formatter) {
	var s = new String(source_double);
	var decimalEndPos = (source_double < 0 ? 1 : 0);

	if (s != "")
	{
		re = new RegExp("\\.", "g");
		s = s.replace(re, formatter.decimalSeparator);

		var separatorPos = s.indexOf(formatter.decimalSeparator, 0);
		if (separatorPos < 0)
		{
			separatorPos = s.length;
		}

		// insert group separators
		separatorPos -= formatter.groupSize;
		while (separatorPos > decimalEndPos)
		{
			s = s.substring(0, separatorPos) + formatter.groupSeparator + s.substring(separatorPos, s.length);
			separatorPos -= formatter.groupSize;
		}
	}
	return s;
}

function checkDonation(productID, priceCents, errorMessage, currency, formatter) {
	var donation = PriceToDouble(document.getElementById("donate_" + productID).value, formatter) * 100.001; // .001 to avoid JS calculation problems

	if (donation < priceCents)
	{
		alert(errorMessage + " " + priceCents / 100 + " " + currency);
		return false;
	}
	return true;
}

// Product multiple images
function showImage(path){
	var bigimage = document.getElementById("shopbigimg");
	if(bigimage) {
		bigimage.src = path;
	}
}

/* Login/Newsletter */

// script for "create a profile" checkbox to enable name/password fields
function setProperties(what, onoff, className) {
	subject = document.getElementById(what)
	subject.disabled = onoff;
	subject.className = className;
}

function setProfileCheck() {
	var createProfileObj = document.getElementById("createprofile");
	if (createProfileObj != null && createProfileObj.checked)
	{
		setProperties("field_username", false, "profile-enabled");
		setProperties("field_password", false, "profile-enabled");
		setProperties("field_password2", false, "profile-enabled");
	}
	else
	{
		setProperties("field_username", true, "profile-disabled");
		setProperties("field_password", true, "profile-disabled");
		setProperties("field_password2", true, "profile-disabled");
	}
}

/* Event calendar */

// Navigates to another year or month on button click
function eventsNavigate(currentLink, currentYear, currentMonth) {
	var ddlEventsYear = document.getElementById('ddlEventsYear');
	var ddlEventsMonth = document.getElementById('ddlEventsMonth');

	// Replace year and month in the "Current Link" with the dropdown selected values.
	var link = currentLink.replace('\/' + currentYear + '\/', '/' + ddlEventsYear[ddlEventsYear.selectedIndex].value + '/');
	if (ddlEventsMonth)
	{
		link = link.replace('\/' + currentMonth + '\/', '/' + ddlEventsMonth[ddlEventsMonth.selectedIndex].value + '/');
	}
	document.location.href = link;
}


/* Search */

// Clearn "Search words" from input box if not changed yet.
function searchOnFocus(txt, origText) {
	if (txt.value == origText)
	{
		txt.value = "";
	}
}

/* Recommend article */

function clickRecommendLink(linkObj) {
	var anchor = window.location.hash;
	if (anchor)
	{
		anchor = anchor.substring(1, anchor.length);
	}
	NewWindow(linkObj.href + (anchor ? '&anchor=' + anchor : ''), 'Tip', '450', '550', 'yes');
	return false;
}

/* Web TV */

// Global vars defined on webtv page: playlistHandlerUrl, channelIDList

// Take #12-23-34 parameters from an URL (channelid, dirid, fileid) and return as array.
function webtvGetParams(url) {
	var paramArray;
	var paramString = url.split(/#/)[1];

	if (paramString)
	{

		// Remove trailling slash if any
		if (paramString.substr(paramString.length - 1, 1) == "/")
		{
			paramString = paramString.substr(0, paramString.length - 1);
		}

		paramArray = paramString.split(/-/);
	}
	return paramArray;
}

// Called on page load to add flicker-free switch to all webtv links on the current page
function webtvReplaceLinks() {
	$('a[href^="/webtv/#"]').click(function() { webtvStartPlayer(this) });
}

// Called by clicks on WebTV links to swtich the video without page reload
// Added to links by webtvReplaceLinks()
function webtvStartPlayer(link) {
	var paramArray = webtvGetParams(link.href);

	var knownChannel = false;

	// Check if channel is allowed by site config
	if (channelIDList)
	{
		for (var i = 0; i < channelIDList.length; i++)
		{
			if (channelIDList[i] == paramArray[0])
			{
				knownChannel = true;
				break;
			}
		}
	}

	// Accept valid channel IDs only
	if (knownChannel)
	{
		// This method is defined on FimlFlip server to allow calls into the Flash file.
		openPlaylist(paramArray[0], paramArray[1], paramArray[2]);
	}
	else
	{
		alert("Invalid channel ID. Configure your Channel IDs in the Admin interface.");
	}
}

// Called on page load to start current video based on anchors in URL
function webtvOnLoadMain(skinurl, cssclass, allowfullscreen, playerurl, width, height, autoplay) {
	// Parse anchor from URL
	var paramArray = webtvGetParams(document.location.href);

	// Defaults to first configured channel
	if (!paramArray)
	{
		paramArray = [channelIDList[0]];
	}

	var knownChannel = false;

	// Check if channel is allowed by site config
	if (channelIDList)
	{
		for (var i = 0; i < channelIDList.length; i++)
		{
			if (channelIDList[i] == paramArray[0])
			{
				knownChannel = true;
				break;
			}
		}
	}

	// Accept valid channel IDs only
	if (knownChannel)
	{

		// This method is defined on FimlFlip server, and uses our "playlistHandlerUrl" global var.
		var playlistUrl = getPlaylistUrl(paramArray[0], paramArray[1], paramArray[2]);

		var flashVars = {
			"style": skinurl,
			"playlist": escape(playlistUrl),
			"eventHandler": "handlePlayerEvent",
			"autoplay": autoplay
		};

		var params = {
			"quality": "high",
			"cssclass": cssclass,
			"allowfullscreen": allowfullscreen,
			"allowScriptAccess": "always",
			"wmode": "transparent"
		};

		swfobject.embedSWF(playerurl, "FlexStreamPlayer", width, height, "9.0.0", null, flashVars, params);

		// Change all links on the page to be "flicker-free" video switch link
		webtvReplaceLinks();
	}
	else
	{
		alert("Invalid channel ID. Configure your Channel IDs in the Admin interface.");
	}
}


/* Session ping */

function sessionPing() {
	var http_request = false;
	if (window.XMLHttpRequest) {
		http_request = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try { http_request = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) {
			try { http_request = new ActiveXObject("Microsoft.XMLHTTP"); }
			catch (e) { }
		}
	}
	if (!http_request) return false;
	http_request.onreadystatechange = function() {
		if (http_request.readyState == 4) {
			var pingTimer = setTimeout(sessionPing, SessionPingInterval);
			var loginState = 2;
			if (http_request.status == 200) {
				var xmldoc = http_request.responseXML;
				var pingNode = xmldoc.getElementsByTagName('ping').item(0);
				loginState = pingNode?pingNode.firstChild.data:3;
				if (loginState == 0) {
					alert(SessionPingTimeoutText);
					clearTimeout(pingTimer);
				}
			}
		}
	}
	http_request.open('GET', '/Default/Modules/Admin/SessionPing.aspx', true);
	http_request.send(null);
}

/* Admin Link icons */

var adminLinkGrid;  // Grid positions for admin icons
var windowSavedWidth; // Save window width to throttle resize event

// Generate admin edit icon HTML based on JSON and move to the location
function addAdminLinks(force) {
	if (windowSavedWidth == jQuery(window).width() && !force) {
		return;
	}
	windowSavedWidth = jQuery(window).width();

	var iconType = { "content": false, "block": false, "layout": false };
	jQuery("#admin_bar input:checked").each(function () {
		iconType[this.name] = true;
	})
	var commentText = "", topPos = { top: 0, left: 0 }, bottomPos = { top: 0, left: 0 };
	var pickerBase = jQuery("#admin_overlay");
	pickerBase.empty(); adminLinkGrid = {}; // reset on resize

	function getIconHtml(key) {
		var locator;
		var iconHtml = ['<div>'];
		// Generate HTML for icons
		for(var i = 0; i < adminlinks.length; i++) {
			if(adminlinks[i].locator === key) {
				locator = adminlinks[i].locator.substring(0, 6);
				if (iconType.content && locator === "page"
					|| iconType.block && locator === "block:"
					|| iconType.layout && locator === "blockg") {
					iconHtml.push('<a target="_blank" class="_' + adminlinks[i].icon
					+ '" title="' + adminlinks[i].tooltip
					+ '" href="' + adminlinks[i].url + '"></a>');
				}
			}
		}
		iconHtml.push('</div>');
		return iconHtml;
	}

	function drawHtml() {
		// Check grid proximity
		var key = "k" + Math.floor(topPos.left/22) + ":" + Math.floor(topPos.top/22);
		var iconHtml = getIconHtml(commentText);

		if (iconHtml.length > 2) {
			if(adminLinkGrid[key]) {
				iconHtml[0] = '<div style="margin-left:' + 22*adminLinkGrid[key] + 'px">';
			} else {
				adminLinkGrid[key] = 0;
			}
			// Mark position to existing grid point nearby
			adminLinkGrid[key] += iconHtml.length-2;
			// HTML generation
			jQuery('<div class="_block">' + iconHtml.join('') + '</div>')
				.appendTo(pickerBase)
				.css("left", topPos.left)
				.css("top", topPos.top)
				.width(bottomPos.left-topPos.left)
				.height(0)
				.find("div")
				.mouseenter({height:bottomPos.top-topPos.top}, function (event){
					jQuery(this).parent().height(event.data.height).addClass("outline");
				})
				.mouseleave(function (){
					jQuery(this).parent().height(0).removeClass("outline");
				});
		}
	}

	jQuery("[id]") //[id]
	// Loop all id's
	.each(function () {
		var children = jQuery(this).contents();
		var jThis, tempPos, tempWidth, tempHeight;
		var phase = 0; // phase of finding dimensions
		// 0: nothing, 1:_start, 2: first element, 3: more elements

		for (var i = 0; i < children.length; i++) {
			jThis = jQuery(children[i]);
			switch (children[i].nodeType) {
				case 8: // COMMENT_NODE

					// There is nothing to draw;
					if (phase === 1
						&& children[i].data.indexOf("_end") >= 0) {
						phase = 0; // reset the automaton
					}

					// There is something to draw;
					if (phase > 1
						&& (children[i].data.indexOf("_end") >= 0
						|| children[i].data.indexOf("_start") >= 0)) {
						drawHtml();
						phase = 0; // reset the automaton
					}

					// Blockgroup, block or other start comment
					if (children[i].data.indexOf("_start") >= 0) {
						commentText = children[i].data.replace("_start", "");
						// Remove "ArticlePage", etc.
						if (commentText.indexOf("page", 0) === 0) {
							commentText = "page";
						}
						phase = 1;
						bottomPos = { top: 0, left: 0 };
					}
					break;
				case 1: // ELEMENT_NODE
					if (phase > 0 && jThis.css("display") !== "none") {
						tempPos = jThis.offset();
						tempWidth = jThis.innerWidth();
						tempHeight = jThis.innerHeight();
						if (phase === 1) {
							phase = 2;
							topPos.left = tempPos.left;
							topPos.top = tempPos.top;
						}
						if (phase > 1) {
								phase = 3;
								tempWidth = tempPos.left + tempWidth;
								tempHeight = tempPos.top + tempHeight;
								bottomPos.left = (bottomPos.left < tempWidth) ? tempWidth : bottomPos.left;
								bottomPos.top = (bottomPos.top < tempHeight) ? tempHeight : bottomPos.top;
						}
					}
					break;
				default:
					break;
			}
		}

		if (phase > 1) {
			drawHtml();
		}
	})
}

// Show/hide admin edit icons or tell the user to reload, saves to server side
function toggleAdminLinks(chk, reloadText) {

	if(chk.checked) {
		if(document.getElementById("admin_overlay")) {
			jQuery("#admin_overlay");
			addAdminLinks(true);
		} else {
			alert(reloadText);
		}
	} else {
		jQuery("#admin_overlay");
		addAdminLinks(true);
	}

	// Save on server side

	var url = "/Default/Chunks/SaveAdminBar.aspx?show" + chk.name + "icons=" + (chk.checked ? "1" : "0");

	jQuery.get(url, function(data) {
		var json = JSON.parse(data);
	}, "json");
}

