/**
 * 
 * LD.index.js
 * (c) LinkDiagnosis.com
 * 
 * 
 * LD index JS library
 * [Begin
 **/


// -- initialize [
var LD = new Object();                              // this is the main object
var RFlashDisplay = new Object();                   // this object controls the output handlers
LD.rootDomain = 'http://www.linkdiagnosis.com';    // where this is deplyoed
// -- initialize ]


// -- this sets that a new report has been requested
LD.start = function(url) {
    if(!Browser.Engine.gecko) {
        window.location.href = '/faq.php#firefox';
        return;
    }
    $('siteurl').value = url;
    LD.hasExtension = false;
    
    setTimeout('LD.startWaited()',5000);
    setTimeout('LD.sendStartSignal()',1000);
};


// -- this tries to connect to the tool to let it know there is a job
LD.sendStartSignal = function() {
    try {
        var element = document.createElement("StartSignalDataElement");
        element.setAttribute("url", document.getElementById('siteurl').value);
        element.setAttribute("key", document.getElementById('server_key').value);
        document.documentElement.appendChild(element);
        
        var evt = document.createEvent("Events");
        evt.initEvent("StartSignalEventBeta", true, false);
        element.dispatchEvent(evt);
    }
    catch(e) {
        LD.start(document.getElementById('siteurl').value);
    }
};


// -- should the tool not respond, its probably because the tool isn't there
LD.startWaited = function() {
    if ($('do_start').value == '') {
        tellUserControl("We were unable to detect our tool extension, our FireFox extension is needed to run reports.");
        LD.mb.options.allowClose = true;
        
        var evt = document.createEvent("Events");
        evt.initEvent("click", true, false);
        $('download_20').dispatchEvent(evt);
    }
    else {
        LD.hasExtension = true;
    }
};


// -- stops the current job
LD.sendKillSignal = function() {
    try {
        var element = document.createElement("ForceShutdownElement");
        document.documentElement.appendChild(element);
        
        var evt = document.createEvent("Events");
        evt.initEvent("ForceShutdownSignalEventBeta", true, false);
        element.dispatchEvent(evt);
    }
    catch(e) { }
};


LD.splashTimers = {
    "progress"  : false,
    "data"      : false,
    "percent"   : false
};
// -- initialize splash timers
LD.initializeSplashTimers = function() {
    // -- set splash timers
    LD.splashTimers["progress"] = setInterval(function(){
        if($("splash_progress").value != "") {
            var msgs = eval("(" + $("splash_progress").value + ")");
            for(var i = 0; i < msgs.length; i++) {
                SplashDisplay.showProgressUser(msgs[i]);
            }
            $("splash_progress").value = "";
        }
    }, 1000);
    LD.splashTimers["percent"] = setInterval(function(){ SplashDisplay.setProgress($("splash_perc").value); }, 900);
    LD.splashTimers["data"] = setInterval(function(){ 
        if($("splash_data").value != "") {
            SplashDisplay.update(eval("(" + $("splash_data").value + ")"));
        }
    }, 1100);
};


// -- redirects back to the home page
LD.bounceHome = function(param) {
    if(param && param.trim() != "") {
        document.location.href = param;
    }
    else {
        document.location.href = '/';
    }
};


// -- this tells the tool a new site report request has been initiated
LD.startIndexedPages = function(url) {
    LD.indexedPages = new Array()   
    tmpUrl = url.toLowerCase();
    if (tmpUrl.search("http://") != 0 && tmpUrl.search("https://") != 0) {
        url = "http://" + url;
    }
    LD.siteUrl = url;
    
    $('siteurl').value = url;
    
    try{
        var element = document.createElement("StartIndexedPagesSignalDataElement");
        element.setAttribute("url", document.getElementById('siteurl').value);
        element.setAttribute("key", document.getElementById('server_key').value);
        document.documentElement.appendChild(element);
        
        var evt = document.createEvent("Events");
        evt.initEvent("IndexedPagesStartSignalEventBeta", true, false);
        element.dispatchEvent(evt);
    }
    catch(e){
        /* */
    }
};


// -- deprecated
LD.print = function(what) {
    // do nothing
    // document.getElementById('debug').innerHTML = document.getElementById('debug').innerHTML + '<br/>' + what;
};


// Get the domain from a url
function getDomain(url) {
    if (!url) return '';
    var temp = url.replace('http://','');
    temp = temp.replace('https://','');
    var temp = temp.split('/');
    return temp[0];
};


// Rid the url of the protocol
function cutDomain(url) {
    var temp = url.replace('http://','');
    temp = temp.replace('https://','');
    return temp.replace(getDomain(url),'' );
};


function escapeHTML(str) {
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
};

function unescapeHTML(html) {
    var htmlNode = document.createElement("DIV");
    htmlNode.innerHTML = html;
    if(htmlNode.innerText)
        return htmlNode.innerText; // IE
    return htmlNode.textContent; // FF
};

function cutString(str,len) {
    if (str) {
        if (str.length > len) {
            str = str.substring(0,len - 3) + "...";
        }
    }
    return str;
};


function sendServerKey() {
    return document.getElementById('server_key').value;
}


function delay_reload_report() {
    var element = document.createElement("ReloadStartSignalDataElement");
    element.setAttribute("url", document.getElementById('siteurl').value);
    element.setAttribute("key", document.getElementById('server_key').value);
    document.documentElement.appendChild(element);
    
    var evt = document.createEvent("Events");
    evt.initEvent("ReloadStartSignalEventBeta", true, false);
    element.dispatchEvent(evt);
}





/* morebrains */
//try {
showm = true;
var bossEngine = true;
var progressCache = new Array();
var progressSize = 4;
function showProgressUser(str) {
    /* do something */
}

function reflush_report() {
    window.location.href = '?q=' + ThisURL + '&f=true';
}
function reload_report() {
    try {
        window.location.href = LD.rootDomain + '/index.php?q=' + $('siteurl').value + '&k=' + $('server_key').value + '&reload=true' + (!LD.basic ? '&report_output=1' : '&report_output=0');
    }
    catch(e) {
        setTimeout("reload_report();", 1500);
    }
}
function hard_reload_report() {
    try {
        window.location.href = LD.rootDomain + '/index.php?q=' + $('siteurl').value + '&k=' + $('server_key').value;
    } catch(e) {
        setTimeout("reload_report();", 1500);
    }
}
function bounceHome(param) {
    if(param && param.trim() != "") {
        LD.bounceHome(param);
    }
    else {
        LD.bounceHome(LD.rootDomain + '/index.php');
    }
}

function pokerOfBeast() {
    // clear splash timers
    clearInterval(LD.splashTimers["progress"]);
    clearInterval(LD.splashTimers["percent"]);
    clearInterval(LD.splashTimers["data"]);
    
    
    if(LD.siteD){
        pokeTheMartian();
        LD.mb.options.allowClose = true;
        
        closeSplash();
        return;
    }
    
    pokeTheBeast();
    LD.mb.options.allowClose = true;
    
    
    if($('cache_age').value != ''){
        if(document.location.href.indexOf("&reload=true") != -1){
            tellUserControl('Did the report reload correctly? If it did not, <a href="#" onclick="reload_report(true); return false;">please click me and I will attempt to reload it again ' + (!LD.basic ? 'using the basic interface' : 'using the enhanced interface') + '</a>.');
        } else {
            tellUserControl('Did the saved report load correctly? If it did not, please click which version to attempt: <a href="' + LD.rootDomain + '/index.php?q=' + $('siteurl').value + '&k=' + $('server_key').value + '&report_output=0">enhanced</a> | <a href="' + LD.rootDomain + '/index.php?q=' + $('siteurl').value + '&k=' + $('server_key').value + '&report_output=1">basic</a>');
        }
        closeSplash();
        
    }
    else {
        closeSplash();
        tellUser('Did the report load correctly? If it did not, <a href="#" onclick="reload_report(true); return false;">please click me and I will attempt to load it again ' + (!LD.basic ? 'using the basic interface' : 'using the enhanced interface') + '</a>.');
    }
}
//} catch(e) { }

function closeSplash() {
    var myFx = new Fx.Scroll($(document.body)).start(0, 508);
    setTimeout("LD.mb.close();", 550);
    return false;
}


function in_array(needle, haystack, argStrict) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
 
    var found = false, key, strict = !!argStrict;
 
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
 
    return found;
}

var copIsOn = false;
function whisperUser(msg, dur) {
    $('LD_Cop').innerHTML = msg;
    if(copIsOn) { return; }
    copIsOn = true;
    $('LD_Cop').fancyShow();
    if(!dur) {
        dur = 3000;
    }
    setTimeout(function(){
        $('LD_Cop').fancyHide();
        copIsOn = false;
    }, dur);
}

var captainIsOn = false;
function tellUser(msg, hold) {
    $('LD_Captain').innerHTML = msg;
    if(captainIsOn) { return; }
    captainIsOn = true;
    $('LD_Captain').show();
    
    var myFx = new Fx.Tween($('LD_Captain'));
    myFx.start('background-color', '#2F8CAB', '#DFDFDF');
    
    var myFx2 = new Fx.Tween($('LD_Captain'));
    myFx2.start('border-top-color', '#2F8CAB', '#CCCCCC');
    
    if(!hold) {
        setTimeout("untellUser();", 10000);
    }
}

function tellUserControl(msg) {
    tellUser('<a href="#" onclick="untellUser(); return false;" style="text-decoration:none;">[X] Close</a> &gt; ' + msg, true);
}

function untellUser() {
    $('LD_Captain').hide();
    captainIsOn = false;
}

var constableInterval = null;
function reprimandUser(msg) {
    
    if(!msg) {
        $('LD_Constable').fancyHide();
        clearInterval(constableInterval);
        
        return;
    }
    
    clearInterval(constableInterval);
    
    $('LD_Constable').innerHTML = msg;
    $('LD_Constable').fancyShow();
    
    constableInterval = setInterval("reprimandUser('');", 25000);
}

var extensionCheckerInterval = null;
var currentExtension = '2.2.41';
var currentExtensionDetails = 'LinkDiagnosis.com FireFox Extension Hotfix: <a onclick="if(typeof(InstallTrigger)!=\'undefined\') {var InstallXPI = {\'Extension Installation\': \'/extension/linkdiagnosis.xpi\'}; InstallTrigger.install(InstallXPI); return false;}" type="application/x-xpinstall" href="/extension/100526/linkdiagnosis.xpi">Install here</a>';
var extensionCheckerAttempts = 0;
function checkForExtension() {
    if($('has_extension_22').value) {
        if(currentExtension > $('has_extension_22').value) {
            clearInterval(extensionCheckerInterval);
            reprimandUser('A new tool version is available, please download the latest version... Your Version: '+$('has_extension_22').value+'... New Version: '+currentExtension);
            tellUserControl(currentExtensionDetails);
        }
        else {
            clearInterval(extensionCheckerInterval);
        }
    }
    else {
        /*
        if(extensionCheckerAttempts > 10 && !$('has_extension_22').value) {
            reprimandUser('We\'re sorry, we cannot detect our Firefox extension installed in your browser. An installation of our Firefox extension is required to generate reports. Thank you!');
            whisperUser('&lt;--- Warning!');
            clearInterval(extensionCheckerInterval);
        }
        */
    }
    extensionCheckerAttempts++;
}

function checkExtension() {
    try {
        var element = document.createElement("HasExtensionElement");
        document.documentElement.appendChild(element);
        
        var evt = document.createEvent("Events");
        evt.initEvent("HasExtensionSignalEventBeta", true, false);
        element.dispatchEvent(evt);
    }
    catch(e) { }
    extensionCheckerInterval = setInterval("checkForExtension();", 2000);
}





BrowserWindow.IncludeJS("/_JS/LD.DAO.js");




// -- onload event logic handler [
LD.basic = false;
window.addEvent('domready', function(){
    try {
        if(HTTPRequest && HTTPRequest.QueryString("oldboss")) {
            bossEngine = false;
        }
    } catch(e) { }
    
    // -- formworks [
    try {
        if($('report_pr').value=='1') {
            $('report_pr_switch').className='gfx-item toggle-switch-on';
        }
        else {
            $('report_pr_switch').className='gfx-item toggle-switch';
        }
    } catch(e) { }
    // -- formworks ]
    
    
    // -- lightbox handler
    LD.ol = new Overlay();
    LD.mb = new MultiBox('multibox', {
        descClassName:'multiBoxDesc', 
        overlay: LD.ol
    });
    
    
    // -- force tool update
    if($('force_download') && $('force_download').value == 1) {
        var evt = document.createEvent("Events");
        evt.initEvent("click", true, false);
        $('download_20').dispatchEvent(evt);
        LD.mb.options.allowClose = true;
    }
    
    
    // -- try to contact the tool
    if($('has_extension_22')) {
        checkExtension();
    }
    
    
    // -- element props
    Element.implement({
        show: function() {
            this.setStyle('display','');
        },
        hide: function() {
            this.setStyle('display','none');
        },
        fancyShow: function() {
            this.fade('in');
        },
        fancyHide: function() {
            this.fade('out');
        }
    });
    
    
    // -- flag prereq perms
    var allowReport = true;
    
    
    // -- check for flash
    /*
    var flashPlayerVersion = deconcept.SWFObjectUtil.getPlayerVersion()
    if(flashPlayerVersion.major < 10 || (flashPlayerVersion.major == 10 && flashPlayerVersion.rev < 12)) {
        reprimandUser('Your Adobe Flash Player is outdated, please update to the latest Flash Player available before continuing.');
        whisperUser('&lt;--- Warning!');
        tellUserControl('You may update your Adobe Flash Player by going here: <a href="http://www.adobe.com/products/flashplayer/">Get Flash</a>. You will be asked to close your browser when you update.');
        allowReport = false;
    }
    */
    
    
    // -- basic/enhanced library loader
    if($('basic_output')) {
        if($('basic_output').value == 1) {
            LD.basic = true;
            BrowserWindow.IncludeJS("/_JS/unflash.js"); 
        }
        else {
            BrowserWindow.IncludeJS("/_JS/flash.js");
        }
    }
    else {
        BrowserWindow.IncludeJS("/_JS/flash.js");
    }
    
    
    // -- simple reload, invoked if the page is refreshed
    var fallback = false;
    if(document.location.href.indexOf("&reload=true") != -1){
        try {
            var ThisURL = decodeURIComponent(HTTPRequest.QueryString("q"));
            if(ThisURL.indexOf("http://") == -1 && ThisURL.indexOf("https://") == -1){
                ThisURL = "http://"+ ThisURL;
            }
            $('siteurl').value = ThisURL;
            
            
            fallback = false;
            
            var evt = document.createEvent("Events");
            evt.initEvent("click", true, false);
            $('fakesplash_link').dispatchEvent(evt);
            LD.mb.options.allowClose = false;
            
            //RFlashDisplay.show();
            
            setTimeout("delay_reload_report();", 3000);
        } catch(e) {
            fallback = true;
        }
    } else {
        fallback = true;
    }
    
    
    // -- hey its a site diagnosis
    LD.siteD =  false;
    if(document.location.href.indexOf(LD.rootDomain + "/site.php") != -1) {
        LD.siteD = true;
    }
    
    
    
    // -- logic switcher
    if(fallback && document.location.href.indexOf("?q=") != -1 && !allowReport){
        // -- can't run, something is missing
        
        alert('Unable to run report, some dependencies are missing.');
    }
    else if(fallback && document.location.href.indexOf("?q=") != -1 && allowReport && !LD.siteD){
        // -- its a link report
        
        var ThisURL = decodeURIComponent(HTTPRequest.QueryString("q"));
        if(ThisURL.indexOf("http://") == -1 && ThisURL.indexOf("https://") == -1){
            ThisURL = "http://"+ ThisURL;
        }
        
        LD.start(ThisURL);
        
        var evt = document.createEvent("Events");
        evt.initEvent("click", true, false);
        if($('cache_age').value != ''){
            $('fakesplash_link').dispatchEvent(evt);
        } else {
            $('splash_link').dispatchEvent(evt);
        }
        LD.mb.options.allowClose = false;
        
        LD.initializeSplashTimers();
        //RFlashDisplay.show();
        
        
    }
    else if(fallback && document.location.href.indexOf("?q=") != -1 && allowReport && LD.siteD){
        // -- its a site report
        
        var ThisURL = getDomain(decodeURIComponent(HTTPRequest.QueryString("q")));
        if(ThisURL.indexOf("http://") == -1 && ThisURL.indexOf("https://") == -1){
            ThisURL = "http://"+ ThisURL;
        }
        
        LD.startIndexedPages(ThisURL);
        
        window.addEvent('domready', function(){
            var evt = document.createEvent("Events");
            evt.initEvent("click", true, false);
            $('splash_link').dispatchEvent(evt);
            LD.mb.options.allowClose = false;
        });
        
        SFlashDisplay.show();
        
        LD.initializeSplashTimers();
    }
    
    
    // -- hide our warners
    if(allowReport) {
        if($('LD_Cop')) { $('LD_Cop').fancyHide(); }
        if($('LD_Captain')) { $('LD_Captain').hide(); }
        if($('LD_Constable')) { $('LD_Constable').fancyHide(); }
    }
    
    if($('LD_Station_Cell') && $('LD_Station_Cell').innerHTML != "") {
        myLightBox.activate($('LD_Station_Cell').innerHTML);
    }
    else if(!Browser.Engine.gecko) {
        if(!Cookie.read("warned_user")) {
            LD.ol.show();
            myLightBox.activate('<span data-label="form_errors"><label class="form_errors_label">Alert</label><fieldset class="form_errors"><div class="error-top"><div class="corner"></div></div><p>Our site works best with FireFox; in fact it will only generate reports with FireFox! <a href="http://www.getfirefox.com">Get FireFox!</a>.</p><div class="error-bottom"><div class="corner"></div></div></fieldset></span>');
            Cookie.write('warned_user', 'true');
            setTimeout(function() {
                LD.ol.hide();
            }, 2500);
            return;
        }
        
    }
    
    
    if(!$('memberGreeting')) {
        var aDiv = new Element('div', {"id": "msg_container"});
        aDiv.setAttribute('class', 'msg_scroll msg_scroll_start');
        aDiv.setStyle('text-align', 'center');
        aDiv.setStyle('padding-top', '3px');
        aDiv.setStyle('padding-left', '10px');
        
        
        /*
        var aL = new Element('span');
        aL.appendText('Partner Content: ');
        aDiv.grab(aL);
        
        var fed = 0;
        
        
        BrowserWindow.IncludeJS("http://www.google.com/jsapi?key=ABQIAAAAOhL0jxemcJ8LL0sASGvRTBToQw_8NSL0t-eWCwBvEaq16MoiqhQvYVWMRZrAOPS36q2u7gSZ1Xqe6Q");
        
        
        google.load("feeds", "1");
        var feed = new google.feeds.Feed("http://linkbuilding.net/feed/"); 
        feed.load(function(result) { 
            if (!result.error && result.feed.entries.length > 0) {
                
                var aL = new Element('a');
                aL.setAttribute('href', result.feed.entries[0].link);
                aL.appendText(result.feed.entries[0].title);
                aDiv.grab(aL);
                
                fed++;
            } 
        }); 
        if(fed) {
            aDiv.appendText(' | ');
        }
        var feed = new google.feeds.Feed("http://searchconcepts.com/feed/"); 
        feed.load(function(result) { 
            if (!result.error && result.feed.entries.length > 0) {
                
                var aL = new Element('a');
                aL.setAttribute('href', result.feed.entries[0].link);
                aL.appendText(result.feed.entries[0].title);
                aDiv.grab(aL);
            } 
        }); 
        
        */
        
        
        
        var newSpan = new Element('span');
        newSpan.setStyle('color', '#FF0000');
        newSpan.appendText('NEW');
        aDiv.grab(newSpan);
        
        aDiv.appendText(': ');
        
        var aL = new Element('a');
        aL.setAttribute('href', 'http://blog.linkdiagnosis.com/2010/08/17/yahoo-boss-will-stick-around-after-bing-merger/');
        aL.appendText('Yahoo! BOSS Will Stick Around After Bing Merger');
        aDiv.grab(aL);
        
        /*
        aDiv.appendText(' | ');
        
        var aL = new Element('a');
        aL.setAttribute('href', 'http://blog.linkdiagnosis.com/2010/05/backlinkextension-manager/');
        aL.appendText('Backlink/Extension Manager');
        aDiv.grab(aL);
        */
        
        /*
        var newSpan = new Element('span');
        newSpan.setStyle('color', '#FF0000');
        newSpan.appendText('We are currently experiencing some technical difficulties with our content providers, running reports may be affected.');
        aDiv.grab(newSpan);
        
        var aL = new Element('span');
        aL.appendText(' Thank you for your understanding and patience.');
        aDiv.grab(aL);
        */
        
        
        /*
        aDiv.appendText(' | ');
        
        var aL = new Element('span');
        aL.appendText('Waving hello from our new home here in amazon!');
        aDiv.grab(aL);
        
        aDiv.appendText(' | ');
        
        var newEm = new Element('em');
        newEm.appendText('Pardon our speed as we move around some of our stuff.');
        aDiv.grab(newEm);
        */
        
        
        
        $('header').grab(aDiv);
    }
    
});
// -- onload event logic handler ]
