var lvWin;
var promoWin;
var vPopupWin;
var jsUrlHash = new urlHashBookmark();

if (typeof(translation) == 'undefined'){
    var translation = {};
    translation[1] = 'A popup window was blocked by your browser.\n'
                        +'To have this site fully functional, you will have to deactivate popup blocker software\n'
                        +'or to configure them to allow popup windows created by this site.';
    translation[2] = 'Please include the \'@\' symbol, the email address should look similar to this: myname@myisp.com';
    translation[3] = 'Spaces in the email address are not allowed, the email address should look similar to this: myname@myisp.com';
    translation[4] = 'You have more than one \'@\' symbol. The email address should look like this: myname@myisp.com';
    translation[5] = 'The email address is too short. The email address should look similar to this: myname@myisp.com';
    translation[6] = 'The domain part of the email address is too short. The email address should look similar to this: myname@myisp.com';
    translation[7] = 'The domain name in the email address is invalid. The email address should look similar to this: myname@myisp.com';
    translation[8] = 'The contents have been copied to your clipboard.\t\n';
}

//default functions
function isUndefined(property){
    return (typeof(property) == 'undefined');
}

function cancel(){ return false;}

//browser helpers
if (typeof(window.offscreenBuffering) != 'undefined')
    window.offscreenBuffering = false;

if (document.layers){
    // reloads page if resized in netscape 4x to keep style
    onresize = function (){if (innerWidth != origWidth || innerHeight != origHeight) { location.reload();}};
    origWidth = innerWidth;
    origHeight = innerHeight;
}

//onerror = handleErr;
function handleErr(msg, url, l){
    txt = 'There was an error on this page.\n\n';
    txt += 'Error: ' + msg + '\n';
    txt += 'URL: ' + url + '\n';
    txt += 'Line: ' + l + '\n';
    txt += 'Click OK to continue.\n\n';
    alert(txt);
    return true;
}

function setStatus(newStatus){
    window.status = newStatus;
    return true;
}

function include(script){
    if (document.getElementById && document.getElementsByTagName && document.createElement &&
        document.getElementByTagName('head')){
        includeDom(script);
    } else {
        document.write('<' + 'script');
        document.write(' type="text/javascript"');
        document.write(' src="' + script + '">');
        document.write('</' + 'script' + '>');
    }
}

function includeDom(script){
    var htmlDoc = document.getElementByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script);
    htmlDoc.appendChild(js);
    return false;
}

function translate(){
    if (!arguments.length) return "";
    if (arguments.length == 1) return translation[arguments[0]];

    var _ = [], out = translation[arguments[0]], i;
    for (i = 1; i < arguments.length; i++) { _.push(arguments[i])}
    i = 0;
    out = out.replace(new RegExp('%%','gim'), '@@@@@@@@@@\0\0@@@@@@@@@@');
    while (1){
        i++;
        var newStr = out.replace(/%s/i, '%' + i + '\\$s');
        if (newStr != out){
            out = newStr;
        } else {
            break;
        }
    }
    for (i = 0; i < _.length; i++){
        var re = new RegExp('%' + (i + 1) + '\\\\\\\$s', 'gim');
        out = out.replace(re, _[i]);
    }
    return out.replace(new RegExp('@@@@@@@@@@\0\0@@@@@@@@@@', 'gim'), '%%');
}

function redirect(win, url, noReplace){
    if (isUndefined(win)){
        if (!isUndefined(window.top)){
            win = window.top;
        } else {
            win = window;
        }
    }
    if ((isUndefined(noReplace) ||
        noReplace == false) &&
        !isUndefined(window.location.replace) &&
        window.location.replace){
        win.location.replace(url);
    } else {
        win.location.href = url;
    }
}

function urlencode(plaintext){
    // The Javascript escape and unescape functions do not correspond
    // with what browsers actually do...
    var SAFECHARS = "0123456789" +                  // Numeric
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +  // Alphabetic
    "abcdefghijklmnopqrstuvwxyz" +
    "-_.!~*'()";                    // RFC2396 Mark characters
    var HEX = "0123456789ABCDEF";

    var encoded = "";
    for (var i = 0; i < plaintext.length; i++ ) {
        var ch = plaintext.charAt(i);
        if (ch == " ") {
            encoded += "+";             // x-www-urlencoded, rather than %20
        } else if (SAFECHARS.indexOf(ch) != -1) {
            encoded += ch;
        } else {
            var charCode = ch.charCodeAt(0);
            if (charCode <= 255) {
                encoded += "%";
                encoded += HEX.charAt((charCode >> 4) & 0xF);
                encoded += HEX.charAt(charCode & 0xF);
            }
        }
    } // for

    return encoded;
};

function setIndex(lst, str){
	for(var i = lst.options.length-1; i>=0;i--) if(lst.options[i].text==str) break;
	lst.selectedIndex = i;
}

function setIndexVal ( lst, str ){
	for ( var i = lst.options.length-1; i >= 0; i-- )
		if ( lst.options [i].value == str )
			break;

	lst.selectedIndex = i;
}

function aaa(name, aaa){
    alert('aaa');
}

function popupWin(name, url, sidk, width, height, left, top, resizable, toolbar, statusbar, dependent,
                  popupBlockedMessage, scrollbars){
    var posStr = 'channelmode=no, fullscreen=no, directories=no, location=no, menubar=no';

    if (!popupBlockedMessage)
        popupBlockedMessage = translate(1);

    posStr += ', toolbar=' + (toolbar?'yes':'no');
    posStr += ', status=' + (statusbar?'yes':'no');
    posStr += (dependent || isUndefined(dependent)?', dependent':'');
    posStr += ', resizable=' + (resizable?'1':'0');
    if (left)
        posStr += ', left=' + left;
    if (top)
        posStr += ', top=' + top;
    if (width)
        posStr += ', width=' + width;
    if (height)
        posStr += ', height=' + height;
    if (scrollbars) 
        posStr += ', scrollbars=1' ;

    if (sidk)
        url = URLParamAdd(url, new Array('sidk', sidk));

    var popupWin = window.open('', name, posStr);
    if (!popupWin){
        alert(translate(1));
        return false;
    }

    var _ = false;
    try{
        _ = popupWin.location.href;
    } catch (e) {}
    if (_ == false || _.indexOf(url) == -1){
        redirect(popupWin, url);
        if (!popupWin.opener)
            popupWin.opener = self;
        if (popupWin.document && popupWin.document.title)
            popupWin.document.title = name;
    }
    if (popupWin.focus)
        popupWin.focus();

    return popupWin;
}

function featLegend() {
    //return popupWin ('featLegend', '/featuresexplained.html', '', 340, 175, (screen.width - 400), 20, false, false, false, true);
    popupWin ('featLegend', '/featuresexplained.html', '', 340, 220, (screen.width - 400), 20, false, false, false, true);
}

function OpenWin ( fvPhoto ){ popupWin ('NewWin', '/showpic.html?PicFilename=' + fvPhoto, '', 340, 265, (screen.width - 400), 20, 
                                               false, false, true); }

function openTerms(path) {

    path = path ? 'path='+path+'&' : '';

    popupWin('terms', '/terms.html?'+path+'popup=1', '', 450, 350, 0, 0, true, false, false, false, false, true);
    return false;
}

function openChat(url) {
    popupWin('chat', url, '', 450, 500, 350, 0, true, false, false, false);
}

function OpenChat ( roomID, username ){
    var winName;
    if ( roomID == 1 ){
        winName = 'Public' + username;
    }else if ( roomID == 11 ){
        winName = 'ChathostOnly' + username;
    }
    popupWin (winName, '/chatrooms.html?roomID=' + roomID, '', 450, 500, 350, 0, true, false, false, false);
}


function openSessWin(sidk, chNick){
    return popupWin ('ses_' + chNick, '/chathost/session.html', sidk, 760, 500, true, false, true, false); }

function syncMailCount(mailCount){
    if (parent.SideBar &&
        parent.SideBar.document.getElementById('mailCount')){
        parent.SideBar.document.getElementById('mailCount').innerHTML = mailCount;
    }
}

function confirmEmail(email) {
    if (!isValidEmail(email)) {
        return translate(29);
    }
    return '';
}

function isValidEmail(email) {
	var filter = /^[-!#$%&'*+\/=?^_`{|}~\w]+(\.[-!#$%&'*+\/=?^_`{|}~\w]+)*@([a-z\d]+(\-+[a-z\d]+)*\.)+[a-z]{2,6}$/i;

    if (!filter.test(email) || email.length > 255) {
        return false;
    }
    return true;
}

function bgHttpRequest(url){
    var xmlObj = null;

    if (window.XMLHttpRequest){
        xmlObj = new XMLHttpRequest();
    } else if (window.ActiveXObject){
        try { xmlObj = new ActiveXObject('MSXML2.XmlHttp'); }
        catch (e) { try { xmlObj = new ActiveXObject('Microsoft.XmlHttp'); }
        catch (e) { try { xmlObj = new ActiveXObject('MSXML.XmlHttp'); }
        catch (e) { try { xmlObj = new ActiveXObject('MSXML3.XmlHttp'); }
        catch (e) {}}}}
    }
    if (xmlObj != null){
        xmlObj.open("GET", url, false);
        xmlObj.send(null);
    } else if (navigator.javaEnabled() && typeof(java) != 'undefined'){
        var req = new java.net.URL(new java.net.URL(window.location.href), url);
        var con = req.openConnection();
        con.setUseCaches(false);
        con.connect();
        var res = con.getLastModified();
    } else {
	xmlObj = window.open ( url, 'closeses', "toolbar=no, width=10, height=10, top=10000, left=10000");
        xmlObj.onload = new function (){xmlObj.close()};
    }
}

function copyToClipBoard(sContents) {
    window.clipboardData.setData("Text", sContents);
    alert(translate(8));
}

function putImage(img1,img2) {
    document.images[img1].src=eval(img2+'.src');
};

function FilterKeys_Numeric(e) {
	var asc = (navigator.appName=='Netscape' ? e.which : event.keyCode);
	return ((asc >= 48) && (asc <= 57));
}

function FilterKeys_Alphanumeric(e) {
	var asc = (navigator.appName=='Netscape' ? e.which : event.keyCode);
	return ((asc >= 48) && (asc <= 57)) || ((asc >= 65) && (asc <= 90)) || ((asc >= 97) && (asc <= 122));
}

function FilterKeys_Email(e) {
	var asc = (navigator.appName=='Netscape' ? e.which : event.keyCode);
	return ((asc >= 48) && (asc <= 57)) || ((asc >= 65) && (asc <= 90)) || ((asc >= 97) && (asc <= 122) || (asc == 95 ) || (asc == 45 ) || (asc == 46 ) || (asc == 64 ));
}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if(cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
            num.substring(num.length - (4 * i + 3));
    return (((sign)?'':'-') + num + '.' + cents);
}

function getURLParam(name){
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var tmpURL = window.location.href;
    var results = regex.exec( tmpURL );
    if( results == null )
        return "";
    else
        return results[1];
}

/*
// Array.unique( strict ) - Remove duplicate values
if (typeof Array.prototype.unique == 'undefined'){
    Array.prototype.unique = function( b ) {
        var a = [], i, l = this.length;
        for( i=0; i<l; i++ ) {
            if( a.indexOf( this[i], 0, b ) < 0 ) { a.push( this[i] ); }
        }
        return a;
    };
}
*/

if ( 'undefined' == typeof Array.prototype.unique )
{
    Array.prototype.unique = function()
    {
        var arr = [];

        this.sort();

        for ( var i = 0; i < this.length; i++ )
        {
            if ( this[ i ] !== this[ i+1 ] )
            {
                arr[ arr.length ] = this[ i ];
            }
        }

        return arr;
    }
}

if ( 'undefined' == typeof Array.prototype.shuffle ){
    Array.prototype.shuffle = function(){
        for (var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
    }
}

var jsCookie = {

    set: function( name, value, secs )
    {
        if ( null == value || 'undefined' == typeof value )
        {
            secs = -1;
        }

    	if ( !secs )
        {
            var expires = '';
        }
        else
        {
    		var date = new Date();
    		date.setTime( date.getTime() + ( secs * 1000 ) );
    		var expires = '; expires=' + date.toGMTString();
    	}

    	document.cookie = name + '=' + value + expires;
    },

    get: function( name )
    {
    	var name = name + '=';
    	var cookies = document.cookie.split( ';' );

    	for ( var i = 0; i < cookies.length; i++ )
        {
    		var cookie = cookies[i];

    		while ( cookie.charAt(0) == ' ' )
            {
                cookie = cookie.substring( 1 );
            }

    		if ( cookie.indexOf( name ) == 0 )
            {
                return cookie.substring( name.length );
            }
    	}

    	return null;
    }
}

function urlHashBookmark()
{
    var oHash = {};

    this.get = function ( key )
    {
        key = key.toUpperCase();

        if ( 'undefined' != typeof oHash[ key ] )
        {
            return oHash[ key ];
        }

        return null;
    }

    this.set = function( key, val, dryRun )
    {
        if ( null == key || 'undefined' == typeof key ) {
            return false;
        }

        var oTemp = oHash;

        if ( null == val || 'undefined' == typeof val ) {
            delete oTemp[ key.toUpperCase() ];
        } else {
            oTemp[ key.toUpperCase() ] = val;
        }

        var tmpHash = [];

        for ( var hashKey in oTemp ){
            tmpHash[ tmpHash.length ] = hashKey + ( null != oTemp[ hashKey ] ? ':' + oTemp[ hashKey ] : '');
        }

        if ( true == dryRun ) {
            return '#'+ tmpHash.join( ';' );
        }

        oHash = oTemp;
        document.location.hash = tmpHash.join( ';' );
    }

    if ( document.location.hash ) {
        var tmpHash = document.location.hash.substring( 1 );

        tmpHash = tmpHash.split( ';' );

        for ( var i = 0; i < tmpHash.length; i++ ) {
            if ( tmpHash[ i ].length > 0 ) {
                var tmpElm = tmpHash[ i ].split( ':' );

                tmpElm[ 0 ] = tmpElm[ 0 ].toUpperCase();

                if ( !oHash[ tmpElm[0] ] ) {
                    oHash[ tmpElm[ 0 ] ] = ( 'undefined' == typeof tmpElm[ 1 ] ) ? null : tmpElm[ 1 ];
                }
            }
        }
    }
}

// This code is in the public domain. Feel free to link back to http://jan.moesen.nu/
function sprintf(){
    if (!arguments || arguments.length < 1 || !RegExp){
        return;
    }
    if (arguments.length == 1 && arguments[0].length){
        arguments = arguments[0];
    }
    var str = arguments[0];
    var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
    var a = b = [], numSubstitutions = 0, numMatches = 0;
    while (a = re.exec(str)){
        var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
        var pPrecision = a[5], pType = a[6], rightPart = a[7];
        //alert(a + '\n' + [a[0], leftpart, pPad, pJustify, pMinLength, pPrecision);
        numMatches++;
        if (pType == '%'){
            subst = '%';
        } else {
            numSubstitutions++;
            if (numSubstitutions >= arguments.length){
                alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\nfor the number of substitution parameters in string (' + numSubstitutions + ' so far).');
            }
            var param = arguments[numSubstitutions];
            var pad = '';
            if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
            else if (pPad) pad = pPad;
            var justifyRight = true;
            if (pJustify && pJustify === "-") justifyRight = false;
            var minLength = -1;
            if (pMinLength) minLength = parseInt(pMinLength);
            var precision = -1;
            if (pPrecision && pType == 'f') precision = parseInt(pPrecision.substring(1));
            var subst = param;
            if (pType == 'b') subst = parseInt(param).toString(2);
            else if (pType == 'c') subst = String.fromCharCode(parseInt(param));
            else if (pType == 'd') subst = parseInt(param) ? parseInt(param) : 0;
            else if (pType == 'u') subst = Math.abs(param);
            else if (pType == 'f') subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) / Math.pow(10, precision): parseFloat(param);
            else if (pType == 'o') subst = parseInt(param).toString(8);
            else if (pType == 's') subst = param;
            else if (pType == 'x') subst = ('' + parseInt(param).toString(16)).toLowerCase();
            else if (pType == 'X') subst = ('' + parseInt(param).toString(16)).toUpperCase();
        }
        str = leftpart + subst + rightPart;
    }
    return str;
}

function URLParamAdd(url, newParams){
    var query = '';
    var params = new Array();
    var found = false;
    var newQuery = '';
    if (typeof newParams[0] == 'string')
        newParams = new Array(newParams);
    
    i = url.indexOf('?');
    if (i != -1){
        query = url.substring(i + 1);
        url = url.substring(0, i);
        params = query.split('&');
    }
    
    if (params.length){
        for (x = 0; x < params.length; x++){
            param = params[x].split('=');
            if (!isUndefined(param) && param[0]){
                found = false;
                for (j = 0; j < newParams.length; j++){
                    if (param[0] == newParams[j][0])
                        found = true;
                }
                if (!found)
                    newQuery += (newQuery?'&':'') + param[0] + '=' + param[1];
            }
        }
    }
    for (j = 0; j < newParams.length; j++){
        newQuery += (newQuery?'&':'') + newParams[j][0] + '=' + newParams[j][1];
    }
    return url + (newQuery?'?' + newQuery:'');
}

function requestURIGet(){
    return window.location.pathname + window.location.search + window.location.hash;
}

var ccExpDatePopup;
function ccExpDateChange(a) {
    var width = 390;
    var height = 140;

    var features = [
            'dependent=yes',
            'dialog=yes',
            'channelmode=no',
            'directories=no',
            'fullscreen=no',
            'location=no',
            'menubar=no',
            'resizable=no',
            'scrollbars=no',
            'status=no',
            'titlebar=no',
            'toolbar=no',
            'width='+width,
            'height='+height,
            'top='+((screen.height-height)/2),
            'left='+((screen.width-width)/2)
        ];

    ccExpDatePopup = window.open(a.href,'ccExpDate', features.join(','));
    ccExpDatePopup.focus();
    return false;
}

function findCoords(e) {
    var posX = 0, posY =0;
    if (!e){e = window.event; }
    if (!e){return [0, 0]; }
    if (typeof(e.pageX) == 'number'){
        posX = e.pageX;
        posY = e.pageY;
    } else {
        if ( typeof(e.clientX) == 'number'){
            posX = e.clientX; posY = e.clientY;
            if (document.body && !(window.opera || window.debug || navigator.vendor == 'KDE')){
                if (typeof(document.body.scrollTop) == 'number') {
                    posX += document.body.scrollLeft;
                    posY += document.body.scrollTop;
                } 
            }
            if (document.documentElement && !(window.opera || window.debug || navigator.vendor == 'KDE')){
                if (typeof(document.documentElement.scrollTop) == 'number') {
                    posX += document.documentElement.scrollLeft;
                    posY += document.documentElement.scrollTop;
                }
            }
        }
    }
    return [posX, posY];
}
