/*
+------------------------------------------------------------------------------+
| Sales-n-Stats                                                                |
| Copyright (c) 2005 - 2006 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 - 2006   |
| 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;

/* 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 isEmail(string) // {{{
{
    if (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) {
        return true;
    } else {
        return false;
    }
} // }}}

function openURL(url, width, height) // {{{
{
    var win = window.top.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';
} // }}}

/* VoIP */

var applet_auto = 0;
var applet_activex = 1;
var applet_java = 2;

function detectAppletType(applet_type) // {{{
{
    if (applet_type != applet_auto) {
        return applet_type;
    }
    // applet type autodetection
    
    // if we are running IE on Win32, load ActiveX applet
    // otherwise use Java applet

    var useActiveX = isIE() && isWindows32();

    return (useActiveX ? applet_activex : applet_java);
} // }}}

function getAppletTypeString(applet_type) // {{{
{
    applet_type = detectAppletType(applet_type);
    var applet_descr = "<Unknown voice applet>";
    if (applet_type == applet_activex) {
        applet_descr = "ActiveX";
    } else if (applet_type == applet_java) {
        applet_descr = "Java";
    }
    return applet_descr;
} // }}}

function getCodebase() // {{{
{
    var location = window.location.href;
    var lastSlash = location.lastIndexOf('/');
    return location.substring(0, lastSlash);
} // }}}

function includeJustLoadApplet(appletType, elementId, width, height) // {{{
{
    document.write(getJustLoadApplet(appletType, elementId, width, height));
} // }}}

function includeWorkingApplet(appletType, remoteIp, remotePort, width, height) // {{{
{
    document.write(getWorkingApplet(appletType, remoteIp, remotePort, width, height));
} // }}}

function getJustLoadApplet(appletType, elementId, width, height) // {{{
{
    appletType = detectAppletType(appletType);

    if (width == null) {
        width = 82;
    }

    if (height == null) {
        height = 74;
    }

    var tag = private_getOpenTag(appletType, width, height, elementId);
    tag += createParamTag('JustLoad', '1');
    tag += private_getCloseTag(appletType);
    return tag;
} // }}}

function getWorkingApplet(appletType, remoteIp, remotePort, elementId, bgColor, width, height) // {{{
{
    appletType = detectAppletType(appletType);

    if (width == null) {
        width = 150;
    }

    if (height == null) {
        height = 20;
    }

    var tag = private_getOpenTag(appletType, width, height, elementId);
    tag += createParamTag('RemotePort', remotePort);
    tag += createParamTag('RemoteHost', remoteIp);
    if (bgColor != null) {
        tag += createParamTag('BackgroundColor' , bgColor);
    }
    tag += private_getCloseTag(appletType);
    return tag;
} // }}}

function private_getOpenTag(appletType, width, height, elementId) // {{{
{
    if (elementId == null) {
        elementId = elementPrefix + identitySeed;
        identitySeed++;
    }
    
    if (appletType == applet_activex) {
        var location = getCodebase() + '/lib/VoiceCom.cab';
        return get_ax_openTag(location, elementId, width, height);
    } else if (appletType == applet_java) {
        return get_java_openTag(
                'personalize/communication/voip/VoiceCom',
                'lib/voicecom.jar', getCodebase(), elementId, width, height);
    } else {
        alert('Debug assertion failed: invalid applet type code');
    }
} // }}}

function private_getCloseTag(appletType) // {{{
{
    if (appletType == applet_activex) {
        return get_ax_closeTag();
    } else if (appletType == applet_java) {
        return get_java_closeTag();
    } else {
        alert('Debug assertion failed: invalid applet type code');
    }
} // }}}

function getAppletStateString(state)
{
    switch (state) {
        case 0: return "Disconnected";
        case 1: return "Connected";
        case 2: return "Timeout";
        case 3: return "On hold";
        case null: return "Not available";
        default: return "<unknown>";
    }
}

var identitySeed;
var elementPrefix = "sns_voip";

if (identitySeed == null) {
    identitySeed = 0;
}

function get_ax_openTag(codebase, elementId, width, height) // {{{
{
    var s = '<OBJECT classid="CLSID:0D66EF3B-7C5B-43A7-9164-C9DCCEA9D273" '
    s += 'width="' + width + '" height="' + height + '" ';
    s += 'codebase="' + codebase + '" id="' + elementId + '">';

    return s;
} // }}}

function get_ax_closeTag() // {{{
{
    return '</OBJECT>';
} // }}}

function get_java_openTag( // {{{
                        code,       /* applet class location */
                        archive,    /* applet jar file(s) */
                        codebase,   /* jar file(s) codebase */
                        elementId,
                        width,      /* applet dimensions */
                        height)
{
    var tag = '<';
    
    var tagName = (isIE() ? 'OBJECT' : 'APPLET');
    tag += tagName;

    if (isIE()) {
        tag += ' codebase="http://java.sun.com/products/plugin/autodl/jinstall-1_4_2-windows-i586.cab#Version=1,3,0,0"';

        tag += ' classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"';
    } else {
        tag += ' code="' + code + '"';
        tag += ' archive="' + archive + '"';
        tag += ' codebase="' + codebase + '"';
    }

    tag += ' width=' + width;
    tag += ' height=' + height;

    tag += ' id="' + elementId + '"';

    tag += '>\r\n';

    if (isIE()) {
        tag += createParamTag('code', code) + '\r\n';
        tag += createParamTag('codebase', codebase) + '\r\n';
        tag += createParamTag('archive', archive) + '\r\n';
    }

    return tag;
} // }}}

function get_java_closeTag() // {{{
{
    return '</' + (isIE() ? 'OBJECT' : 'APPLET') + '>';
} // }}}

function createParamTag(name, value) // {{{
{
    return '<PARAM name="' + name + '" value="' + value + '">';
} // }}}

/* 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 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;
}

} // if (pragma_once == null) ends

