var DEFAULT_CONFIG_URL = "http://www.digital-media-repository.com/dmrs/widget/";
var DEFAULT_COVER_URL ="http://www.digital-media-repository.com/dmrs/cover.do?isbn=";
var DEFAULT_WIDTH = 200;
var DEFAULT_HEIGHT = 400;
//we need to store the params in a global hashmap with the isbn as key to be able to have more than one widget on a page
if (typeof DMRParams == 'undefined') {
    DMRParams = new Array();
}




function openWin(startingPage,w,h,author,title,searchStr,matchesStr,isbn,jumpTo)
{
    largeStartingPage = startingPage;
    var swf = writeSwf(isbn,true,searchStr,matchesStr,jumpTo);
    
  var myLeft =  0;
    var myTop =  0;
    /*try {
        var myLeft =  (screen.availWidth-w)/2;
        var myTop =  (screen.availHeight-h)/2;      
    } catch(e) {}*/        
    var varString = "height="+h+",width="+w+",top=" + myTop + ",left=" + myLeft + ",resizable=1,status=0";  
    var OpenWindow=window.open("", "window", varString);
    OpenWindow.document.write("<HTML>");
    OpenWindow.document.write("<TITLE>"+author+" - "+title+"</TITLE>");
    OpenWindow.document.write("<BODY BGCOLOR='ffffff' leftmargin='0' rightmargin='0' bottommargin='0' topmargin='0'>");
    OpenWindow.document.write("<CENTER>");
    OpenWindow.document.write(swf);
    OpenWindow.document.write("</CENTER>");
    OpenWindow.document.write("</BODY>");
    OpenWindow.document.write("</HTML>");
    OpenWindow.focus();
}

function DMRWidget(isbn, swfArgs){
    if (swfArgs == null || typeof swfArgs == 'undefined')  swfArgs = '';
    //we need to store the params in a global hashmap with the isbn as key to be able to have more than one widget on a page
    DMRParams[isbn]=swfArgs;
    flashInst = getFlashVersion();
    if(flashInst >= 8){
        var myOutput = writeSwf( isbn,false,'','','');
        document.write(myOutput);
      }else{
        var coverImg = DEFAULT_COVER_URL+isbn+"&width=200";
        document.write('<div id="noflash" style="text-align: center;">');
        document.write("<img src='"+coverImg+"' /><br/><br/>To browse and search this book, <br/>please upgrade to the latest version <br/>of the free <a href='http://www.adobe.com/go/getflashplayer' target='_blank'>Adobe Flash Player</a>.</div>");
      }
}

function writeSwf (isbn,large,searchStr,matchesStr,jumpTo)
{
    var myIsbn = isbn;
    var isLarge = large;
    
    if (isParam('https', isbn)) { //if the https parameter was set - rewrite the urls to https
        DEFAULT_CONFIG_URL = replaceStr(DEFAULT_CONFIG_URL, "http://", "https://");
        DEFAULT_COVER_URL = replaceStr(DEFAULT_COVER_URL, "http://", "https://");
    }       
    
    var w = getParam('width', isbn);
    var h = getParam('height', isbn);
    var sUrl = getParam('serviceUrl', isbn);
    var cUrl = getParam('configUrl', isbn);
    
    var sPage = '';
    var mySearchStr = '';
    var myMatchesStr = '';
    var myJumpTo = '';  
    
    if (isLarge == true){
        sPage = largeStartingPage;
        mySearchStr = searchStr;
        myMatchesStr = matchesStr;
        myJumpTo = jumpTo;
    }else{
        sPage = getParam('startingPage', isbn);
    }


    
    var width = checkWidth(w);
    var height = checkHeight(h);
    //var serviceUrl = checkServiceUrl(sUrl);
    var configUrl = checkConfigUrl(cUrl);
    var startingPage = checkStartingPage(sPage);
    var myPageHost = document.location.hostname;    
    var myLocalHost = window.location.protocol; 
    if (isEmptyOrUndefined(myPageHost)) {myPageHost='local';}   
    if (isEmptyOrUndefined(myLocalHost)) {myLocalHost='';}          

    //must
    var must = [];
    //I have to add the prefix DMR to be able to differentiate my properties of this object from the ones assigned to Object.prototype
    must['DMRisbn'] = isbn;
    must['DMRwidth'] = width;           
    must['DMRheight'] = height;
    must['DMRpageHost'] = myPageHost;   
    must['DMRLocalHost'] = myLocalHost; 
    if(!isEmptyOrUndefined(myJumpTo)) must['DMRjumpTo'] = myJumpTo;                     
    must['DMRconfigUrl'] = configUrl;
    must['DMRstartingPage'] = startingPage;
    must['DMRsearchStr'] = mySearchStr;
    must['DMRmatchesStr'] = myMatchesStr;

    var swfParams = getSwfParams(must, isbn);
    var swfLocation = DEFAULT_CONFIG_URL+"DMRWidget.swf"; 
    //var swfLocation = "DMRWidget.swf"; 
    var myString = "";
    scale = "scale";
    if (isLarge){
        width = "100%";
        height = "100%";
        scale = "exactfit";
    }

    myString +=("<div style='margin-right:4px'>");
    myString +=("<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'");
            myString +=("id='DMRWidget' width='"+width+"' height='"+height+"' align='left' ");
            myString +=("codebase='http" + (isParam('https', isbn)?"s":"") + "://www.adobe.com/go/getflashplayer'>");
            myString +=("<param name='movie' value='"+swfLocation+"?" + swfParams + "' />"); // edited by djn
            myString +=("<param name='quality' value='high' />");
            myString +=("<param name='FlashVars' value='"+swfParams+" '/>");
            myString +=("<param name='allowScriptAccess' value='always' />");
            myString +=("<param name='allowFullScreen' value='true' />");           
            myString +=("<param name='scale' value='"+scale+"' />");
            myString +=("<param name='salign' value='lt' />");
            myString +=("<embed src='"+swfLocation+"?" + swfParams + "' quality='high' bgcolor='#ffffff'"); // edited by djn
            myString +=("width='"+width+"' height='"+height+"' name='DMRWidget' align='left' ");
            myString +=("play='true' ");
            myString +=("loop='false' ");
            myString +=("quality='high' ");
            myString +=("scale='"+scale+"'");
            myString +=("salign='lt' ");
            myString +=("allowScriptAccess='always' ");
            myString +=("allowFullScreen='true' ");         
            myString +=("type='application/x-shockwave-flash' ");
            myString +=("pluginspage='http://www.adobe.com/go/getflashplayer'> ");
            myString +=("</embed>");
    myString +=("</object>");
    myString +=("</div>");
    return myString;
}

/********************************** Mustard Lab's detect flash methods start here *************************************/
b = navigator.userAgent.toLowerCase();
if ( (b.indexOf('msie') != -1) && (b.indexOf('win') != -1) && (b.indexOf('opera') == -1) ) {
    document.writeln('<script language="VBscript">');
    document.writeln('Function detectActiveXControl(activeXControlName)');
    document.writeln('  on error resume next');
    document.writeln('  detectActiveXControl = False');
    document.writeln('  detectActiveXControl = IsObject(CreateObject(activeXControlName))');
    document.writeln('End Function');
    document.writeln('</scr' + 'ipt>');
}
function getFlashVersion(){
    var installedVersion = 0;
    if ( (b.indexOf('msie') != -1) && (b.indexOf('win') != -1) && (b.indexOf('opera') == -1) ) {
        for (var i=3; i<10; i++){
            if(detectActiveXControl("ShockwaveFlash.ShockwaveFlash."+i) == true) installedVersion = i;
        }
    } else {
        if (navigator.plugins["Shockwave Flash"]) {
            var pluginDesc = navigator.plugins["Shockwave Flash"].description;
            installedVersion = parseInt( pluginDesc.charAt( pluginDesc.indexOf(".")-1 ) );
        }
        if(b.indexOf("webtv") != -1) installedVersion = 3;  
    }
    return installedVersion;
}
/********************************** Mustard Lab's detect flash methods end here *************************************/

function getParam (paramStr, isbn){
    var arg = DMRParams[isbn].split(',');
    var len = arg.length;
    for (a=0;a<len;a++){
        var par = arg[a].split('=')
        if (par[0] == paramStr) return par[1];
    }
    return false;
}

//returns true if the parameter is set to true or yes
function isParam(paramStr, isbn) {
    return (getParam(paramStr, isbn)=='true' || getParam(paramStr, isbn)=='yes' || getParam(paramStr, isbn)=='True' || getParam(paramStr, isbn)=='Yes')
}

function checkWidth (width){
    var w = width;
    if (w == 0 || isNaN(w)) w = DEFAULT_WIDTH
    //if (isNaN(w)) w = DEFAULT_WIDTH
    return w;
}

function checkHeight (height){
    var h = height;
    if (h == 0 || isNaN(h)) h = DEFAULT_HEIGHT
    //if (isNaN(h)) h = DEFAULT_HEIGHT
    return h;
}
/*
function checkServiceUrl (ServiceUrl){
    var sU = ServiceUrl;
    if (!sU) sU = DEFAULT_SERVICE_URL;
    
    return sU;
}
*/
function checkConfigUrl (ConfigUrl){
    var cU = ConfigUrl;
    if (!cU) cU = DEFAULT_CONFIG_URL;
    
    return cU;
}

function checkStartingPage (startPage){
    var n = 1;
    if (isNaN(startPage) || startPage < 1) return n
        return startPage
}

function getSwfParams (obj, isbn) {
    

    var str = "";
    var alreadySetParameter = new Array();
    //split configured parameters at comma
    var arg = DMRParams[isbn].split(',');
    var len = arg.length;
    //iterate over all configured parameters
    for (a=0;a<len;a++){
        //split name-value pairs
        var par = arg[a].split('=');
        //get parameter name
        var parameterName = par[0];
        var parLen = par.length;
        //get the parameter value
        var parameterValue = par[1];
        //if there was one or more = in the value these will be splitted into further array elements, which we need to add these to the parameterValue
        if (parLen > 2){
            for (var i=2 ;i<parLen;i++){
                //replace possible & with ___ because they would crash the parameter string. Flash will later replace this again
                parameterValue += "="+replaceStr(par[i],'&','____');
            }
        }
        //check if there are default values in the must-Hash; Those will overwrite the configured ones
        for (var i in obj){
            //regard only properties of this object flagged with the prefix DMR
            if (i.length > 3 && i.indexOf("DMR")==0) {
                i = i.substring(3);     
                if (i==parameterName) {
                    parameterValue = obj["DMR" + i];
                }
            }
        }
        alreadySetParameter[parameterName] = true;
        str += parameterName+"="+parameterValue+"&";
    }
    
    for (var i in obj){ 
        //regard only properties of this object flagged with the prefix DMR
        if (i.length > 3 && i.indexOf("DMR")==0) {
            i = i.substring(3);
            if (!alreadySetParameter[i]) {
                str += i+"="+obj["DMR" + i]+"&";    
            }
        }
    }
    //alert (str)
    return str;
}

function replaceStr(str, oldStr, newStr)
{
    regExp = new RegExp(oldStr, "gi");
    results = str.replace(regExp, newStr);
    return results;
}

function isEmptyOrUndefined(item) {
    if (item == null || typeof item == 'undefined' || item == '' || item == 'undefined') {return true;} else {return false;}
}// JavaScript Document