var loaderClsid = 'C53BDC3D-19A0-4062-BF34-0897A4E6A6A2';
var loaderMimeType = 'application/wildpockets-loader-plugin';
var loaderPluginDllname = 'Wild Pockets Loader Plugin';
var loaderRelease = 1; var loaderMajor = 0; var loaderMinor = 9; var loaderBuild = 15079;
var loaderVersionStr = loaderRelease+','+loaderMajor+','+loaderMinor+','+loaderBuild;
var loaderCabURL = 'http://www.wildpockets.com/common/WildPocketsLoader-15079.cab';
var loaderXpiURL = 'http://www.wildpockets.com/common/WildPocketsLoader-15079.xpi';


var wpPlatformUnsupportedImage = 'http://www.wildpockets.com/imagelib/plugin/download-plugin-mac.jpg';
var wpBrowserUnsupportedImage  = 'http://www.wildpockets.com/imagelib/plugin/browser-compatible.jpg';
var wpDownloadPluginImage      = 'http://www.wildpockets.com/imagelib/plugin/download-plugin-firefox.jpg';
var wpUpdatePluginImage        = 'http://www.wildpockets.com/imagelib/plugin/update-plugin.jpg';
var wpImageWidth = 720;
var wpImageHeight = 539;
 
function createPocket(ObjectID, Width, Height, Mode, Pocket, Service, Uid, SessionKey, Parameters) {
    document.writeln(createPocketString(ObjectID, Width, Height, Mode, Pocket, null, Service, Uid, SessionKey, Parameters));
}

function createPocketNew(Parameters) {
    document.writeln(createPocketStringNew(Parameters));
}

function createPocketStringNew(Parameters) {
    return createPocketString(Parameters["id"],Parameters["width"],Parameters["height"],Parameters["mode"],Parameters["guid"],"",Parameters["service"],Parameters["uid"],Parameters["sessionkey"],Parameters);
}


function addSessionCookie(name,value,expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie = name + "=" + value + ";expires="+exdate.toGMTString();
}
function updateParameters(Parameters) {
    if (Parameters['dllname'] == 'Wild Pockets Loader Plugin') {
        Parameters['clsid'] = loaderClsid
        Parameters['mimetype'] = loaderMimeType
        Parameters['dllname'] = loaderPluginDllname;
        Parameters['verrelease'] = loaderRelease;
        Parameters['vermajor'] = loaderMajor;
        Parameters['verminor'] = loaderMinor;
        Parameters['verbuild'] = loaderBuild;
        Parameters['verstring'] = loaderRelease+','+loaderMajor+','+loaderMinor+','+loaderBuild;
        Parameters['caburl'] = loaderCabURL;
        Parameters['xpiurl'] = loaderXpiURL;
    } 
}

function isPluginInstalled(Parameters) {

    updateParameters(Parameters);
    pluginInstalled = false;
    // Check what version of the plugin is installed and determine if it is up-to-date
    // with what this page is offering.
    if (navigator && navigator.plugins) {
        var wpPlugin = navigator.plugins[Parameters['dllname']];
        
        if (wpPlugin) {
            pluginInstalled = true;

        }
    }
    
    // If not mozilla...
    if (pluginInstalled == false) {
        try 
        {
            // Try to instanciate a new activeX object
            var slControl = new ActiveXObject('WildPockets.Loader');

            pluginInstalled = true;
        }
        catch (e) 
        {
            // Error. Plugin not installed.
        }
    }
    return pluginInstalled;
}

function isPluginUpToDate(Parameters) {

    updateParameters(Parameters);

    // Check what version of the plugin is installed and determine if it is up-to-date
    // with what this page is offering.
    pluginUpToDate = false;
    if (navigator && navigator.plugins) {
        var wpPlugin = navigator.plugins[Parameters['dllname']];
        if (wpPlugin) {
            var wpPluginDesc = wpPlugin.description;
            var wpPluginVer = new RegExp(Parameters['dllname']+' (.*)').exec(wpPluginDesc)[1];
            var parts = new RegExp('([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)').exec(wpPluginVer);
            var release = parts[1]; var major = parts[2]; var minor = parts[3]; var build = parts[4];
            
            if (Parameters['verrelease'] < release) {
                pluginUpToDate = true;
            }
            else if (Parameters['verrelease'] > release) {
                pluginUpToDate = false;
            }
            else {
                if (Parameters['vermajor'] < major) {
                    pluginUpToDate = true;
                }
                else if (Parameters['vermajor'] > major) {
                    pluginUpToDate = false;
                }
                else {
                    if (Parameters['verminor'] < minor) {
                        pluginUpToDate = true;
                    }
                    else if (Parameters['verminor'] > minor) {
                        pluginUpToDate = false;
                    }
                    else {
                        if (Parameters['verbuild'] <= build) {
                            pluginUpToDate = true;
                        }
                        else {
                            pluginUpToDate = false;
                        }
                    }
                }
            }
        }
    }
    
    // If the mozilla check failed, try the IE check
    if (pluginUpToDate == false) {
        try 
        {
            var slControl = new ActiveXObject('WildPockets.Loader');
		pluginUpToDate = true;
            
        }
        catch (e) 
        {
            // Error. Plugin not installed.
        }
    }
    
    return pluginUpToDate;
}


function createPocketString(ObjectID, Width, Height, Mode, Pocket, Quality, Service, Uid, SessionKey, Parameters) {

    updateParameters(Parameters);
    
    htmlout = '';

    var WidthCSS = Width+"px";
    var HeightCSS = Height+"px";
    if (Width==0) {
        Width = "100%";
        WidthCSS = "100%";
    }
    if (Height==0) {
        Height = "100%";
        HeightCSS = "100%";
    }

    var qsParam = new Array();
    var query = window.location.search.substring(1);
    var parms = query.split('&');
    for (var i=0; i<parms.length; i++) {
        var pos = parms[i].indexOf('=');
        if (pos > 0) {
            var key = parms[i].substring(0,pos);
            var val = parms[i].substring(pos+1);
            qsParam[key] = val;
        }
    }

    // Test for ActiveX and InstallTrigger support
    var supportActiveX = false;
    var supportInstallTrigger = false;
    
    try {
        if (ActiveXObject) {
            supportActiveX = true;
        }
    } catch (e) {
    }
    
    try {
        if (InstallTrigger) {
            supportInstallTrigger = true;
        }
    } catch(e) {
    }

    var showMoz = true;
    var showIE = true;
    var supportedBrowser = true;
    
    if (supportActiveX && supportInstallTrigger) {
        // Here's a weird case. We support InstallTrigger and ActiveX.
        // Not sure how you'd end up here, but possibly the ActiveX plugin
        // for Firefox will get you here. Let's only display the Mozilla
        // block, in this case.
        showMoz = true;
        showIE = false;
    } else if (supportActiveX) {
        // We only support ActiveX. We're in Internet Explorer, or something
        // similar.
        showMoz = false;
        showIE = true;
    } else if (supportInstallTrigger) {
        // We must be in Firefox, or something very similar.
        showMoz = true;
        showIE = true; // I'm not sure why we display the IE block in this
                       // case, but I leave it here for historical reasons.
    } else {
        supportedBrowser = false;
    }
    
    var supportedArchitecture=true;
    var pluginInstalled = false;
    var pluginUpToDate = false;

    if (navigator && navigator.platform) {
        var platform=navigator.platform;
        if(!platform.match("Win")) {
            supportedArchitecture=false;
        }
    }
    
    pluginInstalled = isPluginInstalled(Parameters);
    pluginUpToDate = isPluginUpToDate(Parameters);

    if (!supportedArchitecture) {
        htmlout += wp_imageResizer(wpPlatformUnsupportedImage, WidthCSS, HeightCSS, "");
    } else if (!supportedBrowser) {
        htmlout += wp_imageResizer(wpBrowserUnsupportedImage, WidthCSS, HeightCSS, "");
    } else {

        // Show ActiveX block
        if (showIE) {
            htmlout +=
                '<object id="' + ObjectID + '"' +
                ' classid="CLSID:' + Parameters['clsid'] + '"' +
                ' codebase="' + Parameters['caburl'] + '#version=' + Parameters['verstring'] + '"' +
                ' width="' + Width + '"' +
                ' height="' + Height + '">' +
                '<param name="identifier" value="' + ObjectID + '"></param>' +
                '<param name="deferred" value="1"></param>' +
                '<param name="defertimeout" value="5"></param>';
            for (var key in Parameters) {
                htmlout += '<param name="' + key + '" value="' + Parameters[key] + '"></param>';
            }
            if (Mode) {
                htmlout +=
                    '<param name="mode" value="' + Mode + '"></param>';
            }
            if (Pocket) {
                htmlout +=
                    '<param name="open" value="' + Pocket + '"></param>';
            }
            if (Service && Uid && SessionKey) {
                htmlout +=
                    '<param name="service" value="' + Service + '"></param>' +
                    '<param name="uid" value="' + Uid + '"></param>' +
                    '<param name="sessionkey" value="' + SessionKey + '"></param>';
            }
        }
        // Show Mozilla block
        if (showMoz) {
            if (!pluginInstalled) {
                // plugin not installed, offer to install fresh
                htmlout += wp_imageResizer(wpDownloadPluginImage, WidthCSS, HeightCSS, "installWildpocketsFirefoxWin('"+Parameters['dllname']+"', '"+Parameters['xpiurl']+"');");
            } else if (pluginInstalled && !pluginUpToDate) {
                htmlout += wp_imageResizer(wpUpdatePluginImage, WidthCSS, HeightCSS, "installWildpocketsFirefoxWin('"+Parameters['dllname']+"', '"+Parameters['xpiurl']+"');");
            } else {
                htmlout +=
                    '<embed name="' + ObjectID + '"' +
                    ' identifier="' + ObjectID + '"' +
                    ' deferred="1" defertimeout="5"' +
                    ' type="' + Parameters['mimetype'] + '"' +
                    ' width="' + Width + '"' +
                    ' height="' + Height + '"';
                for (var key in Parameters) {
                    htmlout += ' ' + key + '="' + Parameters[key] + '"';
                }
                if (Mode) {
                    htmlout +=
                        ' mode="' + Mode + '"';
                }
                if (Pocket) {
                    htmlout +=
                        ' open="' + Pocket + '"';
                }
                if (Service && Uid && SessionKey) {
                    htmlout +=
                        ' service="' + Service + '"' +
                        ' uid="' + Uid + '"' +
                        ' sessionkey="' + SessionKey + '"';
                }
                htmlout += '></embed>';
            }
        }
        // End ActiveX block
        if (showIE) {
            htmlout += '</object>';
        }
    }
    
    return htmlout;
}

function installWildpocketsFirefoxWin(wildpocketsPluginDllname, wildpocketsXpiURL) {
    if (wildpocketsXpiURL == "" ) {
        wildpocketsXpiURL = loaderXpiURL;
    }
    eval('params = { "' + wildpocketsPluginDllname + '": { URL: "' + wildpocketsXpiURL + '" } };');
    InstallTrigger.install(params);
}

function pocketPerform(id, command, args) {
    try {
        getPocket(id).perform(command,args);
        return;
    } catch (e) {
        setTimeout(function() { pocketPerform(id, command, args); }, 100);
        return;
    }
}

function pocketEvaluate(id, command, args) {
    try {
        var result = getPocket(id).evaluate(command,args);
        return result;
    } catch (e) {
        return;
    }
}

function getPocket(id) {
    return window.document[id];
}

function wp_urlencode(clearString) {
    var output = '';
    var x = 0;
    clearString = clearString.toString();
    var regex = /(^[a-zA-Z0-9_.]*)/;
    while (x < clearString.length) {
        var match = regex.exec(clearString.substr(x));
        if (match != null && match.length > 1 && match[1] != '') {
            output += match[1];
            x += match[1].length;
        } else {
            if (clearString[x] == ' ')
                output += '+';
            else {
                var charCode = clearString.charCodeAt(x);
                var hexVal = charCode.toString(16);
                output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
            }
            x++;
        }
    }
    return output;
}

function wp_urldecode(encodedString) {
    var output = encodedString;
    var binVal, thisString;
    var myregexp = /(%[^%]{2})/;
    while ((match = myregexp.exec(output)) != null
                && match.length > 1
                && match[1] != '') {
        binVal = parseInt(match[1].substr(1),16);
        thisString = String.fromCharCode(binVal);
        output = output.replace(match[1], thisString);
    }
    return output;
}

function wp_randomString() {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = 8;
    var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    return randomstring;
}

function wp_addResizeEvent(func) {
    var oldonresize = parent.onresize;
    if (typeof parent.onresize != "function") {
        parent.onresize = func;
    } else {
        window.onresize = function() {
            oldonresize();
            func();
        }
    }
}

function wp_imageResizer(img, WidthCSS, HeightCSS, onClick) {
    var divId = wp_randomString();
    var imgId = wp_randomString();
    var htmlout = 
        '<div id="' + divId + '" style="width:' + WidthCSS + '; height:' + HeightCSS + ';">' +
        '<table width="100%" height="100%" cellspacing="0" cellpadding="0"><tr><td align="center" valign="middle">' +
        '<img id="' + imgId + '" src="'+img+'" onclick="' + onClick + '">' +
        '<script language="javascript">' +
            'var f = function() {' +
                'var d = document.getElementById("' + divId + '");' +
                'var i = document.getElementById("' + imgId + '");' +
                'if (d.parentNode.offsetWidth==0 && d.parentNode.offsetHeight==0) { setTimeout(f,50); }' +
                'var x = d.parentNode.offsetWidth;' +
                'var y = x * ' + wpImageHeight + ' / ' + wpImageWidth + ';' +
                'if (x > ' + wpImageWidth + ') { x = ' + wpImageWidth + '; y = ' + wpImageHeight + '; }' +
                'if (y > d.parentNode.offsetHeight) { x = d.parentNode.offsetHeight * ' + wpImageWidth + ' / ' + wpImageHeight + '; y = d.parentNode.offsetHeight; }' +
                'i.style.width = x + "px"; i.style.height = y + "px";' +
            '};' +
            'wp_addResizeEvent(f); f();' +
        '</script>' +
        '</td></tr></table></div>';
    return htmlout;
}
