// v11-2011.11.24

function sendRPC(url) {
    var newScript = document.createElement('script');
    newScript.src = url;
    newScript.type = "text/javascript";
    document.body.appendChild(newScript);
}
function forceReload() {
    window.location.reload(true);
}
///////////////////////////////////////
// EXTENSIONS
document.getElementsById = function(id){
    var nodes = document.getElementsByTagName('*');
    var matches = new Array();
    for(i=0;i<nodes.length;i++){
        if(nodes[i].id == id) matches[matches.length] = nodes[i];
    }
    return matches;
}
function isEmpty(obj) {
    var name;
    for (name in obj)
        return false;
    return true;
}
function isSet(varname) {
    return(typeof(window[varname]) != 'undefined');
}
///////////////////////////////////////
// EVENTS
function attachEventHandlerFunction(sEventName, element, handlerFunction) {
    if (element.addEventListener) {
        element.addEventListener(sEventName, handlerFunction, false);
    } else if (element.attachEvent) {
        element.attachEvent('on' + sEventName, handlerFunction);
    } else {
        element['on' + sEventName] = handlerFunction;
    }
}
function getBrowserEventObject(e){
    //if(window.event != null) {
    //    return event;
    //}
    //return e;
    var evt = e || window.event;
    return evt;
}
function preventDefaultEvent(e) {
    var evt = e || window.event;
    if (evt.preventDefault) {
        evt.preventDefault();
    } else {
        evt.returnValue = false;
    }
    return false;
}
///////////////////////////////////////
// PAGE LOAD GENERAL EVENTS
attachEventHandlerFunction('load', window, frameBuster );
function frameBuster() {
    if (window != window.top)
        window.top.location.href= document.location.href;
}
//attachEventHandlerFunction('beforeunload', window, wbCloseWin );
//function wbCloseWin() {
//    processAjax(true,'get','/pages/general/close.ajax.php','', false );
//}

//setInterval(triggerAdReload, 120000);
//function triggerAdReload() {
//    document.body.innerHTML += '';
//}

////////////////////////////////////////
// DEBUGING
function docWrite(text) {
    document.body.innerHTML += '<br>' + text;
}
var errorFirst = true;
function sendErr(desc,url,line) {
    if (url.indexOf('wordbuddy.com')>=0 || url.indexOf('localhost')>=0 || url.indexOf('127.0.0.1')>=0 || url.indexOf('192.168.1.')>=0) {
        var qs = 'url='+encodeURIComponent(url)+'&line='+encodeURIComponent(line)+'&desc='+encodeURIComponent(desc)+'&first='+(errorFirst ? 1 : 0);
        //if (url && url.substr(url.length-3) != '.js') qs +='&source='+encodeURIComponent(document.documentElement.innerHTML);
        if (typeof debugAjaxResponseText != 'undefined' && debugAjaxResponseText != '') qs +='&ajax_response='+encodeURIComponent(debugAjaxResponseText);
        //for (var prop in window) {
        //    qs += '&var["'+encodeURIComponent(prop)+'"]='+encodeURIComponent(window[prop]);
        //}
        processAjax(true,'post','/pages/general/jserr.ajax.php', qs);
        errorFirst = false;
    }
    return(true);
}
window.onerror=sendErr;

////////////////////////////////////////
// COOKIES
function getCookie(name) {
  var results = document.cookie.match ( '(^|;) ?'+name+'=([^;]*)(;|$)' );
  if (results) return(unescape(results[2]));
    else return null;
}
function eraseCookie(name) {
    createCookie(name,"",-1);
}
function setCookie(name, value, days, path, domain, secure) {
  var cookie_string = name+"="+escape(value);
  if (days) {
    var expires = new Date();
    expires.setTime(expires.getTime()+(days*24*60*60*1000));
    cookie_string += "; expires=" + expires.toGMTString();
  }
  if (path) cookie_string += "; path=" + escape ( path );
  if (domain) cookie_string += "; domain=" + escape ( domain );
  if (secure) cookie_string += "; secure";
  document.cookie = cookie_string;
}
////////////////////////////////////////
// OBJECTS
//Object.prototype.isNumeric = function() {
//    if (this === '') return false;
//    return !isNaN(this.valueOf() * 1);
//}
function objToStr(o) {
    if (typeof o == 'object') {
        var childrenStr;
        for (var child in o) {
            if (child != 'document' && child != 'crlf' && child != 'parent') {
                var chStr = objToStr(o[child]);
                if (chStr != '') childrenStr += (child + ': ' + chStr);
            }
        }
        return(childrenStr);
    } else if (typeof o == 'undefined') {
        return('(undefined)');
    } else if (typeof o == 'string' || typeof o == 'number') {
        return(o.toString());
    } else {
        return('');
    }
}

////////////////////////////////////////
// STRINGS
String.prototype.trim = function() {
    return this.replace(/^[\s\u3000]+|[\s\u3000]+$/g, '');
    };
String.prototype.escapeHtml = function () {
   return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); // .replace(/'/g,'&#39;').replace(/"/g,'&quot;')
   };
String.prototype.urlEncode = function () {
   return this.replace(/&/g,'%26').replace(/ /g,'+').replace(/:/g,'%3A').replace(/\?/g,'%3F').replace(/\//g,'%2F');
   };
var crlf = String.fromCharCode(13) + String.fromCharCode(10);
////////////////////////////////////////
function browserIsIE() {
  if (navigator.userAgent.indexOf("MSIE") != -1)
    return(true);
  else
    return(false);
}
function browserIsFirefox() {
  if (navigator.userAgent.indexOf("Firefox") != -1)
    return(true);
  else
    return(false);
}
function browserIsNavigator() {
  if (navigator.userAgent.indexOf("Navigator") != -1)
    return(true);
  else
    return(false);
}
function browserIsOpera() {
  if (navigator.userAgent.indexOf("Opera") != -1)
    return(true);
  else
    return(false);
}
function browserIsUnknown() {
  if (navigator.userAgent.indexOf("MSIE") == -1
  &&  navigator.userAgent.indexOf("Firefox") == -1
  &&  navigator.userAgent.indexOf("Navigator") == -1
  &&  navigator.userAgent.indexOf("Opera") == -1 )
    return(true);
  else
    return(false);
}
///////////////////////////////////////////////
function browserIsIE6() {
  if (navigator.userAgent.indexOf("MSIE 6.0;") != -1)
    return(true);
  else
    return(false);
}
////////////////////////////////////////////////
function OSisWindows() {
  if (navigator.platform.toLowerCase().indexOf("win") != -1)
    return(true);
  else
    return(false);
}
function osIsMac() {
  if (navigator.platform.toLowerCase().indexOf("mac") != -1)
    return(true);
  else
    return(false);
}
function osIsUnix() {
  if (navigator.platform.toLowerCase().indexOf("unix") != -1)
    return(true);
  else
    return(false);
}
function osIsLinux() {
  if (navigator.platform.toLowerCase().indexOf("linux") != -1)
    return(true);
  else
    return(false);
}
function osIsUnknown() {
  if (navigator.platform.toLowerCase().indexOf("win") != -1
  &&  navigator.platform.toLowerCase().indexOf("mac") != -1
  &&  navigator.platform.toLowerCase().indexOf("unix") != -1
  &&  navigator.platform.toLowerCase().indexOf("linux") != -1 )
    return(true);
  else
    return(false);
}
//////////////////////////////////////////////////////////////////////////////
// Ad Blocker Detection
setTimeout('detect_blocker()', 10000);
function detect_blocker() {
    var divAd = document.getElementById('ad_bottom');
    if (divAd) {
        testAdsBlocked = (divAd.offsetHeight == 0) ? 1 : 0;
        if (testAdsBlocked != prevAdsBlocked) {
            processAjax(true,'get','/pages/user/adsblocked.ajax.php', "ads_blocked=" + testAdsBlocked, null);
        }
    }
}
//////////////////////////////////////////////////////////////////////////////
// Hdr/Ftr Functions
function livehelp() {
    window.open ("/pages/help/helponlinechat.php", "wordbuddy_online_help","width=250,height=425,resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,menubar=no,copyhistory=no,status=no,titlebar=no");
    return(false);
}
function openPrivPol() {
    window.open ("/pages/general/privacypolicy.php", "winPrivacyPolicy","width=600,height=500,resizable=yes,scrollbars=no,toolbar=no,location=no,directories=no,menubar=no,copyhistory=no"); return(false);
}
function openTOS() {
    window.open ("/pages/general/termsofuse.php", "winTermsOfService","width=800,height=800,resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,menubar=no,copyhistory=no"); return(false);
}
////////////////////////////////////////////////////////////////////////////////
// HTML
function imgPreload(urlSrc) {
    var imgPreload = document.createElement('img');
    imgPreload.style.height = "0px";
    imgPreload.style.width  = "0px";
    imgPreload.src = urlSrc;
    document.body.appendChild(imgPreload);
}
////////////////////////////////////////////////////////////////////////////////
// SCREEN POSITIONING
function absPosX(elmt) {
    var pos = 0;
    if (elmt.offsetParent) {
        do { pos += elmt.offsetLeft;
        } while (elmt = elmt.offsetParent);
        return pos;
    }
}
function absPosY(elmt) {
    var pos = 0;
    if (elmt.offsetParent) {
        do { pos += elmt.offsetTop;
        } while (elmt = elmt.offsetParent);
        return pos;
    }
}
////////////////////////////////////////////////////////////////////////////////
// AUDIO
function htmlAudio(dir, id) {
    var html = "<object width='16' height='16'>"
             + "<param name='movie' value='/flash/mp3player.swf'>"
             + "    <embed src='/flash/mp3player.swf' "
             + "           FlashVars='filename=/"+dir+"%2F"+id+".mp3' "
             + "           quality='high' "
             + "           wmode='transparent' "
             + "           width='16' height='16' "
             + "           allowScriptAccess='sameDomain' "
             + "           allowFullScreen='false' "
             + "           type='application/x-shockwave-flash' "
             + "           pluginspage='http://www.macromedia.com/go/getflashplayer' /> "
             + "</object>";
    return(html);
}

////////////////////////////////////////////////////////////////////////////////
// STUDY FONT SIZE
var fontSizeTimerID;
var fontSizePixels;
var fontSizeMobile;
function adjFontSize(mobile, pxDir) {
    var FONT_SIZE_MAX = 96;
    var FONT_SIZE_MIN = 8;

    fontSizeMobile = mobile;
    for (var i=0; i<document.styleSheets.length; i++) {
        var styleSheet = document.styleSheets[i];
        if (typeof styleSheet.rules != 'undefined') { //IE
            styleSheet.cssRules = styleSheet.rules;}
        if (styleSheet.href == null || styleSheet.href == '' || styleSheet.href.search(/localhost|wordbuddy|192\.168\.1\./g) >= 0) { // no external (page: FF = null, IE == '')
            if (styleSheet.cssRules && styleSheet.cssRules.length > 0) {
                for (var j=0; j<styleSheet.cssRules.length; j++) {
                    var rule = styleSheet.cssRules[j];
                    if (rule && rule.selectorText == '.vocab') {
                        fontSizePixels = new Number(rule.style.fontSize.replace(/px/,''));
                        if (!isNaN(fontSizePixels) && !isNaN(pxDir) ) {
                            var pxDelta = pxDir * (fontSizePixels <= 15 ? 1 : 2);
                            fontSizePixels = fontSizePixels + pxDelta;
                            if (fontSizePixels >= FONT_SIZE_MIN && fontSizePixels <= FONT_SIZE_MAX) {
                                rule.style.fontSize = fontSizePixels+'px';
                                if (typeof fontSizeTimerID != 'undefined') clearTimeout(fontSizeTimerID);
                                fontSizeTimerID = setTimeout(serverAdjFontSize, 1000 );
                            }
                        }
                    }
                }
            }
            if (typeof fontSizePixels != 'undefined' && !isNaN(fontSizePixels)) {
                fontSizeExample = fontSizePixels <= 14 ? fontSizePixels : Math.floor(14 + (fontSizePixels - 14)/2.8);
                for (var j=0; j<styleSheet.cssRules.length; j++) {
                    var rule = styleSheet.cssRules[j];
                    if (rule && rule.selectorText == '.exmpl') rule.style.fontSize = fontSizeExample+'px';
                }
            }
        }
    }
}
function serverAdjFontSize() {
    processAjax(true, 'get', '/pages/user/adjuststudyfontsize.ajax.php', 'mobile='+fontSizeMobile+'&fontsize='+fontSizePixels );
}
// Popup Menus ////////////////////////////////////////////////////////////////////
function createPopupMenuShell(elmtParent) {
    var wordMenu = document.getElementById('word_popup_menu');
    if (wordMenu) wordMenu.parentNode.removeChild(wordMenu);
    wordMenu = document.createElement('div');
    wordMenu.id = 'word_popup_menu';
    wordMenu.style.zIndex = '999';
    wordMenu.style.left = (absPosX(elmtParent)+10) + "px";
    wordMenu.style.top = (absPosY(elmtParent)+6) + "px";
    wordMenu.onmouseout = function(e) {// see: http://www.quirksmode.org/js/events_mouse.html
        if (!e) var e = window.event;
        var toElement = (e.relatedTarget) ? e.relatedTarget : e.toElement;
        while (toElement && toElement.id != 'word_popup_menu')
            toElement = toElement.parentNode;
        if (!toElement)
            this.parentNode.removeChild(this);
    };
    wordMenu.onclick = function(e) {if (this.parentNode)this.parentNode.removeChild(this);};
    var elmtA = document.createElement('a');
        elmtA.innerHTML = "<img src='/images/closebox12.gif' height='12' width='12' />";
        elmtA.onmouseup = function(e){this.parentNode.parentNode.removeChild(this.parentNode);return(preventDefaultEvent(e));};
        elmtA.href = "javascript:void(0);";
        //elmtA.style.width = '12px'; // ie
        elmtA.style.textAlign = 'right'; // ie
        elmtA.style.display = 'block';
        elmtA.style.cssFloat = 'right';
        wordMenu.appendChild(elmtA);
    return(wordMenu);
}
function clickOutOfPopupMenu(e) {
        if (!e) var e = window.event;
        var elTarg = (e.target || e.srcElement);
        if (elTarg) {
            while (elTarg && elTarg.id != 'word_popup_menu')
                elTarg = elTarg.parentNode;
            if (!elTarg && document.getElementById('word_popup_menu')) {
                var el = document.getElementById('word_popup_menu');
                if (el) el.parentNode.removeChild(el);
            }
        }
    }
    attachEventHandlerFunction('mousedown', document, clickOutOfPopupMenu );
function mobileMenu(elmtParent,aryLinks) {
    var popupMenu = createPopupMenuShell(elmtParent);
    for (var link in aryLinks) {
        popupAddLink(popupMenu,aryLinks[link][0],aryLinks[link][1],aryLinks[link][2]);
    }
    document.body.appendChild(popupMenu);
}
function popupAddLink(popupMenu, url, text, urlIcon) {
    var elmtA = document.createElement('a');
        elmtA.innerHTML = (typeof urlIcon == 'undefined' ? '' : "<img src='"+urlIcon+"' height='12' width='12' /> ")+text;
        elmtA.href = url;
        popupMenu.appendChild(elmtA);
}
////////////////////////////////////////////////////////////////////////////////
function newCaptcha(elID) {
    var targetNode = document.getElementById(elID);
    var captchaSrc = targetNode.src;
    captchaSrc = captchaSrc.substring(0,captchaSrc.lastIndexOf(".")+4); // extract image name from image source (i.e. cut off any randomn number [from below] at end)
    captchaSrc += "?"+Math.round(Math.random()*100000); // add random number to prevent browser/isp caching
    targetNode.src = captchaSrc;
}
