/*
/*
+------------------------------------------------------------------------------+
| Sales-n-Stats                                                                |
| Copyright (c) 2005 - 2007 Creative Development <info@creativedevelopment.biz>|
| All rights reserved.                                                         |
+------------------------------------------------------------------------------+
| PLEASE READ  THE FULL TEXT OF SOFTWARE LICENSE AGREEMENT IN THE  "COPYRIGHT" |
| FILE PROVIDED WITH THIS DISTRIBUTION.  THE AGREEMENT TEXT  IS ALSO AVAILABLE |
| AT THE FOLLOWING URL: http://www.sales-n-stats.com/license_agreement.html    |
|                                                                              |
| THIS  AGREEMENT EXPRESSES THE TERMS AND CONDITIONS ON WHICH YOU MAY USE THIS |
| SOFTWARE PROGRAM AND ASSOCIATED DOCUMENTATION THAT CREATIVE DEVELOPMENT, LLC |
| REGISTERED IN ULYANOVSK, RUSSIAN FEDERATION (hereinafter referred to as "THE |
| AUTHOR")  IS  FURNISHING  OR MAKING AVAILABLE TO  YOU  WITH  THIS  AGREEMENT |
| (COLLECTIVELY,  THE "SOFTWARE"). PLEASE REVIEW THE TERMS AND  CONDITIONS  OF |
| THIS LICENSE AGREEMENT CAREFULLY BEFORE INSTALLING OR USING THE SOFTWARE. BY |
| INSTALLING,  COPYING OR OTHERWISE USING THE SOFTWARE, YOU AND  YOUR  COMPANY |
| (COLLECTIVELY,  "YOU")  ARE ACCEPTING AND AGREEING  TO  THE  TERMS  OF  THIS |
| LICENSE AGREEMENT. IF YOU ARE NOT WILLING TO BE BOUND BY THIS AGREEMENT,  DO |
| NOT  INSTALL  OR USE THE SOFTWARE. VARIOUS COPYRIGHTS AND OTHER INTELLECTUAL |
| PROPERTY  RIGHTS PROTECT THE SOFTWARE. THIS AGREEMENT IS A LICENSE AGREEMENT |
| THAT  GIVES YOU LIMITED RIGHTS TO USE THE SOFTWARE AND NOT AN AGREEMENT  FOR |
| SALE  OR  FOR TRANSFER OF TITLE. THE AUTHOR RETAINS ALL RIGHTS NOT EXPRESSLY |
| GRANTED BY THIS AGREEMENT.                                                   |
|                                                                              |
| The Initial Developer of the Original Code is Creative Development LLC       |
| Portions created by Creative Development LLC are Copyright (C) 2005 - 2007   |
| Creative Development LLC. All Rights Reserved.                               |
+------------------------------------------------------------------------------+
*/

/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */

var sns_js_pragma_once;
if (sns_js_pragma_once != null) {
    alert('Debug assertion failed: SnS.js cannot be included more than once');
} else {
sns_js_pragma_once = 0;


var _windowId = null;

function DecHex(d)
{
    var hex = "0123456789ABCDEF";
    var h = hex.substr(d & 15,1);
    while (d > 15) { d >>= 4; h = hex.substr(d & 15, 1) + h; }

    return h;
}

function getWindowId()
{
    if (_windowId == null) _windowId = DecHex(Math.random() * 0x7FFFFFFF);
    return _windowId;
}

/* Sns-specific */

function getDisplayCode(needDisplay)
{
    return (needDisplay ? '' : 'none');
}

function setDisplayElement(elementName, disp) // {{{
{
	var element = document.getElementById(elementName);
	if (element == null) {
		return false;
	}
	try {
		element.style.display = disp;
	} catch (err) {
		alert(elementName + ": " + err.description + "\nTried to set display to \"" + disp + "\"");
		return false;
	}
	return true;
} // }}}

function setDisplayElementGroup(groupName, display) // {{{
{
	setDisplayElement(groupName, display);
	
	var i = 1;
	while (setDisplayElement((groupName + i), display)) {
		i++;
	}
} // }}}

function hideElement(elementId) // {{{
{
	return setDisplayElement(elementId, 'none');
} // }}}

function showElement(elementId) // {{{
{
	return setDisplayElement(elementId, '');
} // }}}

function hideElementGroup(groupName) // {{{
{
	setDisplayElementGroup(groupName, 'none');
} // }}}

function showElementGroup(groupName) // {{{
{
	setDisplayElementGroup(groupName, '');
} // }}}

/* Misc */

function getCookie(cookiename)
{
	var cookiestring = "" + document.cookie;
	var index1 = cookiestring.indexOf(cookiename + "=");
	if (index1 == -1) return "";
	var index2 = cookiestring.indexOf(';', index1);
	if (index2 == -1) index2 = cookiestring.length;
	return cookiestring.substring(index1 + cookiename.length + 1, index2);
}

function escapeForHtml(str) // {{{
{
    str = str.replace(/&/g, '&amp;');
    str = str.replace(/&amp;#/g, '&#');
    str = str.replace(/</g, '&lt;');
    str = str.replace(/>/g, '&gt;');
    str = str.replace(/\r\n/g, '<BR>');
    str = str.replace(/\n/g, '<BR>');
    return str;
} // }}}

function getEmailRegex()
{
	return /[^\s,:]+@[^\s,:]{2,}[^\s,:.]/;
}

function getUrlRegex()
{
	return /(((((H|h)(T|t)|(F|f))(T|t)(P|p)((S|s)?))\:\/\/)?(www.|[a-zA-Z0-9].)[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,6}(\:[0-9]{1,5})*(\/($|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-]+))*)/;
}

function underlineLinks(html)
{
	var position = 0;
	var emailRegex = getEmailRegex();
	var urlRegex = getUrlRegex();

	var fReplaceOnce = function (string, search, replace, startIndex) {
		if (search.length == 0) return string;
		if (string.length == 0) return string;

		var index = string.indexOf(search, startIndex);
		if (index == -1) return string;
		if (index == 0) return replace + string.substring(index + search.length, string.length);

		return string.substring(0, index) + replace + string.substring(index + search.length, string.length);
	};

	var fDecorateUrl = function (url) {
		var linkText = url;
		if (url.indexOf('://') == -1) {
			url = 'http://' + url;
		}
		return '<a target="_blank" href="' + url + '">' + linkText + '</a>';
	};

	var fDecorateEmail = function (email) {
		return '<a href="mailto:' + email + '">' + email + '</a>';
	};

	var fDecorate = function (range, substring, fDecorator) {
		var original = toTest.substring(range.index, range.lastIndex);
		var decorated = fDecorator(original);
		html = fReplaceOnce(html, original, decorated, position);
		position += range.index + decorated.length;
	};

	var fExecRegex = function (regex, string) {
		var range = regex.exec(string);
		if (range != null) {
			range.lastIndex = range.index + range[0].length;
		}

		return range;
	};

	while (position < html.length) {
		var toTest = html.substring(position, html.length);
		var emailRange = fExecRegex(emailRegex, toTest);
		var urlRange = fExecRegex(urlRegex, toTest);

		if (emailRange != null && urlRange != null) {
			if (urlRange.index >= emailRange.index) {
				fDecorate(emailRange, toTest, fDecorateEmail);
			} else {
				fDecorate(urlRange, toTest, fDecorateUrl);
			}
		} else if (emailRange != null) {
			fDecorate(emailRange, toTest, fDecorateEmail);
		} else if (urlRange != null) {
			fDecorate(urlRange, toTest, fDecorateUrl);
		} else {
			return html;
		}
	}

	return html;
}

function isEmail(string) // {{{
{
	return string.search(getEmailRegex()) != -1;
} // }}}

function openURL(url, width, height) // {{{
{
    var win = window.open(url, "_blank", "status=yes,toolbar=no,menubar=no,location=no,width=" + width + ",height=" + height);
    
    return (win != null);
} // }}}

function getIFrameDocument(ifrm) // {{{
{
    var doc;
    if (ifrm.contentDocument) {
        doc = ifrm.contentDocument;
    } else if (ifrm.contentWindow) {
        doc = ifrm.contentWindow.document;
    } else if (ifrm.document) {
        doc = ifrm.document;
    } else {
        alert('IFRAME document was not found');
    }

    return doc;
} // }}}

function getKeyCode(event) // {{{
{
    var keyCode;
    if (event) {
        keyCode = event.keyCode;
    } else if (window.event) {
        keyCode = window.event.keyCode;
    }
    return keyCode;
} // }}}

/* Browser detection */

function isReadyStateAvailable() // {{{
{
    var f = document.createElement("IMG");
    return f.readyState == "uninitialized";
} // }}}

function isAgentIE() // {{{
{
    return navigator.appName == "Microsoft Internet Explorer";
} // }}}

function isAgentOpera() // {{{
{
    return navigator.userAgent.indexOf("Opera") >= 0;
} // }}}

function isIE() // {{{
{
    return isAgentIE() && isReadyStateAvailable();
} // }}}

function isOpera() // {{{
{
    // By default Opera is running in IE6 emulation mode, we need to detect it
    return isAgentOpera() || (isAgentIE() && !isReadyStateAvailable());
} // }}}

function isNetscape() // {{{
{
    return navigator.userAgent.indexOf("Netscape") != -1;
} // }}}

function isFireFox() // {{{
{
    return navigator.userAgent.indexOf("Firefox") != -1;
} // }}}

function isMozilla() // {{{
{
    return !isAgentIE() && navigator.userAgent.indexOf("Mozilla") != -1;
} // }}}

function isGecko() // {{{
{
    return navigator.userAgent.indexOf("Gecko") != -1;
} // }}}

function isWindows32() // {{{
{
    return navigator.platform == 'Win32';
} // }}}

/* SCRIPT tag - related */
// Initialization {{{
var scriptUpdateIntervals;

if (scriptUpdateIntervals == null) {
	scriptUpdateIntervals = new Array();
	scriptUpdateURLs = new Array();
	scriptTagNames = new Array();
	abortUpdateScripts = new Array();
	scriptLastIndex = 0;
} // }}}

function getScriptIndex(scriptName) // {{{
{
	for(var i = 0; i < scriptLastIndex; i++) {
		if (scriptTagNames[i] == scriptName) {
			return i;
		}
	}
	return null;
} // }}}

function startScriptUpdate(scriptName, scriptURL, interval) // {{{
{
	scriptIndex = getScriptIndex(scriptName);
	if (scriptIndex == null) {
		scriptIndex = scriptLastIndex++;
	}
	
	scriptUpdateIntervals[scriptIndex] = interval;
	scriptUpdateURLs[scriptIndex] = scriptURL;
	scriptTagNames[scriptIndex] = scriptName;
	abortUpdateScripts[scriptIndex] = false;

	doScriptUpdate(scriptIndex);

	scriptLastIndex++;
} // }}}

function doScriptUpdate(index) // {{{
{
	var tempURL = scriptUpdateURLs[index];
	if (tempURL.indexOf('?') != -1) {
		tempURL = tempURL + "&";
	} else {
		tempURL = tempURL + "?";
	}
	tempURL = tempURL + "dummy=" + new Date().getTime();

	if (!abortUpdateScripts[index]) {
        try {
		reloadScript(scriptTagNames[index], tempURL);
        } catch (err) {
            alert("Error in doScriptUpdate: "+err.description);
        }
		window.setTimeout(
                'doScriptUpdate(' + index + ')',
                scriptUpdateIntervals[index]);
	} else {
		abortUpdateScripts[index] = false;
	}
} // }}}

function performingScriptUpdate(scriptName) // {{{
{
	index = getScriptIndex(scriptName);
	if (index != null) {
		return abortUpdateScripts[index];
	}
} // }}}

function abortScriptUpdate(scriptName) // {{{
{
	index = getScriptIndex(scriptName);
	if (index != null) {
		abortUpdateScripts[index] = true;
	}
} // }}}

function snsShowScriptIFrame(id, url) // {{{
{
  try {
      var trackerIFrameObj;
      if (document.frames && navigator.userAgent.indexOf("Mac_PowerPC") != -1) {
          trackerIFrameObj = document.frames[id];
      } else {
          trackerIFrameObj = document.getElementById(id);
      }
      var IFrameDoc = getIFrameDocument(trackerIFrameObj);
      IFrameDoc.write("<html><body><script src='"+url+"'></script></body></html>");
      IFrameDoc.close();
  } catch (err) {
      alert("snsShowScriptIFrame err:"+err.description);
  }

  return false;
} // }}}

function reloadScript(scrObjName, newURL) // {{{
{
	var head = document.getElementsByTagName('HEAD').item(0);
	var scriptTag = document.getElementById(scrObjName);
    if (scriptTag) {
        scriptTag.parentNode.removeChild(scriptTag);
    }

    // safari/ie on macos
    if (navigator.userAgent.indexOf("Safari") != -1 || navigator.userAgent.indexOf("Mac_PowerPC") != -1) {
        var tempIFrame=document.createElement('iframe');
        tempIFrame.setAttribute('id',scrObjName);
        tempIFrame.style.border='0px';
        tempIFrame.style.position = 'absolute';
        tempIFrame.style.top = 0;
        tempIFrame.style.left = 0;
        tempIFrame.style.width = 0;
        tempIFrame.style.height = 0;
        tempIFrame.style.zIndex = 0;
        tempIFrame.style.visibility = "hidden";
        tempIFrame.frameBorder = "no";
        tempIFrame.marginWidth = 0;
        tempIFrame.marginHeight = 0;
        document.body.appendChild(tempIFrame);
        if (document.frames && navigator.userAgent.indexOf("Mac_PowerPC") != -1) {
            tempIFrame.src = newURL;
        } else {
            setTimeout('snsShowScriptIFrame("'+scrObjName+'", "'+newURL+'")',200);
        }
    } else {
        var script = document.createElement('SCRIPT');
        script.type = 'text/javascript';
        script.id = scrObjName;
        script.src = newURL;
        head.appendChild(script);
    }

} // }}}

function retrieveGetParameter(paramName)
{
    var search = document.location.search;
    if (search == null || search == '') return null;
    if (search.charAt(0) == '?') search = search.substr(1);
    var params = search.split('&');
    for (var paramIndex in params) {
        var data = params[paramIndex].split('=');
        if (data[0] == paramName) return unescape(data[1]);
    }

	return null;
}

function appendUrlSeparationChar(url)
{
    var href = url;
    var lastChar = href.charAt(href.length - 1);
    var containsQ = href.indexOf('?') != -1;
    var containsA = href.indexOf('&') != -1;

    if (!containsQ) {
        href += '?';
    } else {
        if ((!containsA && lastChar != '?') ||
            (containsA && lastChar != '&')) {

            href += '&';
        }
    }

    return href;
}

function appendTemplateSetHint(url)
{
	var hint = retrieveGetParameter('tsh');
	if (hint == null) return url;
	return appendUrlSeparationChar(url) + 'tsh=' + hint;
}

function reportMessagesSent()
{
	var count = 0;
	while (count++ < 5) {
		try {
			window.parent.messagesSent();
			return true;
		} catch (err) {}
	}
	return false;
}

function openSkypeChat(skypeId)
{
	window.opener.openSkypeLink(skypeId);
}

function openSkypeLink(skypeId)
{
	window.location = 'skype:' + skypeId + '?call';
}

function centerWindow(wnd)
{
    if (wnd == null) wnd = window;

    var width = window.innerWidth == null
        ? window.document.body.clientWidth
        : window.innerWidth;

    var height = window.innerHeight == null
        ? window.document.body.clientHeight :
        window.innerHeight;

    var left = (screen.width - width) / 2;
    var top = (screen.height - height) / 2;

    wnd.moveTo(left, top);
}

} // if (pragma_once == null) ends

