//hardcoded values
var IsApplet;
var timeout=500;
var FirmCode=100441;
var ProductCode=6100;
var AgentUrl="http://www.wibu.com/P6/TestShop";
var TraderURL="http://89.244.16.90/codemeter/Trader/Relay.asmx" 
var PriceCurrency="EUR";
var MAXPRODUCT=13;

//global variables
var selectedStick;
var checkEntry;
var lastErr;
var lastErrMsg;
var expDays = 30;
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
var iteration = 1;

function checkLogin() {
   if((document.login.login.value == "") || (document.login.password.value == "")) {
      alert("Bitte geben Sie Ihren Usernamen und Passwort an.");
      return(false);
   } else return (true);
}
function checkForm2() {
   if((document.login2.login.value == "") || (document.login2.password.value == "")) {
      alert("Bitte geben Sie Ihren Usernamen und Passwort an.");
      return(false);
   } else return (true);
}
function cookieEnabled()
{
  cookieEnabled=navigator.cookieEnabled;
  if (!cookieEnabled) {
  	setCookie('cookieTest', 'true');
  	if (getCookie('cookieTest')==null) {
    	alert("Ihr Browser unterstützt keine Cookies. Bitte aktivieren Sie Cookies und starten Sie den Browser erneut!");
    }
  }
}

// name - name of the cookie
// value - value of the cookie
// [expires] - expiration date of the cookie (defaults to end of current session)
// [path] - path for which the cookie is valid (defaults to path of calling document)
// [domain] - domain for which the cookie is valid (defaults to domain of calling document)
// [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
// * an argument defaults when it is assigned null as a placeholder
// * a null placeholder is not required for trailing omitted arguments
function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

// name - name of the desired cookie
// * return string containing value of specified cookie or null if cookie does not exist
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

// name - name of the cookie
// [path] - path of the cookie (must be same as path used to create cookie)
// [domain] - domain of the cookie (must be same as domain used to create cookie)
// * path and domain default if assigned null or omitted if no explicit argument proceeds
function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" + 
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

//reads the last error and the errormessage into the appr. global variables
function GetLastErr()
{
  if (IsApplet) {
    lastErr=mCmTrigger.GetLastErrorCode();
    lastErrMsg=mCmTrigger.GetLastErrorMessage();
  }  
  else {
    lastErr=mCmTrigger.LastErrorCode;
    lastErrMsk=mCmTrigger.LastErrorMessage;
  }  
}

function InitBoxesInt()
{ 
  mCmTrigger.FirstBox();
  GetLastErr();  
  if ( lastErr != 0 ) {
    //alert(lastErrMsg);
    var entry = document.createElement("option");
    entry.text = "Kein CM-Stick";
    entry.value = "0-0";
    return;
  }
  
  var position  = 1;
  var BoxMask;
  var BoxSerial;
  while (lastErr==0) {
  	isCorrect = false;
    if (IsApplet) {
      BoxMask=mCmTrigger.GetBoxMask();
      BoxSerial=mCmTrigger.GetBoxSerial();
    }
    else {
      BoxMask=mCmTrigger.BoxMask;
      BoxSerial=mCmTrigger.BoxSerial;
    }
    var entry = document.createElement("option");
    entry.text = BoxMask + "-" + BoxSerial;
    entry.value = entry.text;
    entry.selected = true;
    //Check product exists on stick
    mCmTrigger.IsEntryAvailable(FirmCode, ProductCode, 0);
    GetLastErr();   
    if(BoxMask!="0" && lastErr==0) { 
    	isCorrect = true;
    	document.getElementsByName("BoxList")[0].add(entry, position);
    	if(entry.value==getCookie('stick')) break;
    }
    mCmTrigger.NextBox();
    GetLastErr();   
    position++;
  } 
  if((position==2||entry.value==getCookie('stick'))&&isCorrect) {
  	//go on, if only 1 stick or same stick
    setCookie('stick',entry.value);
    document.getElementById ("hiddenBoxList").innerHTML = "<input type=\"hidden\" name=\"BoxList\" value=\""+entry.value+"\">"; 
    document.shoppingcart.submit();
    return;
  }
  document.getElementById ("check").style.visibility = "hidden";
  document.getElementById ("plugin").style.visibility = "visible";
  
}

//initialise the combobox in the current page
//the box has to be named "BoxList"
function InitBoxes()
{
  if (IsApplet)
    window.setTimeout("InitBoxesInt()",timeout);
  else
    InitBoxesInt();  
} // InitBoxes()

//return_to_page - boolean; if true, the browser returns to the calling page
function saveSelectedStick()
{
  if (getCookie('stick')!=null) {
    deleteCookie('stick');
  }
  var selectedStick=document.getElementById('BoxList').value;
  if (selectedStick=="") {
    return false;
  }
  else {
    setCookie('stick',selectedStick);
	return true;
  }
}//saveSelectedStick

function UpdateUnitCounter(id)
{  
  if(iteration==1) InsertObject();
  var strBox = getCookie('stick');
  if (strBox==null) {
	alert("Please select a CM-Stick!");
	return "";  
  }

  var strParts  = strBox.split("-");
  if ( strParts.length != 2 )
  {
    alert("Invalid Box serial number:" + strBox );
    return "";
  }

  if (IsApplet) {
    //proxy settings missing!
    var m=parseInt(strParts[0], 10);
    var s=parseInt(strParts[1], 10);
    mCmTrigger.SetBoxMask(m);
    mCmTrigger.SetBoxSerial(s);
    //mCmTrigger.FirstBox();
    mCmTrigger.SetFirmCode(FirmCode);
    mCmTrigger.SetAgentUrl(AgentUrl);
    mCmTrigger.SetTraderUrl(TraderURL);
    mCmTrigger.SetPackageName(id);
    mCmTrigger.SetPriceCurrency(PriceCurrency);
  }
  else {
    //mCmTrigger.SetAutoProxy();
    mCmTrigger.BoxMask	= strParts[0];
    mCmTrigger.BoxSerial 	= strParts[1];
    mCmTrigger.FirmCode	= FirmCode;
    mCmTrigger.AgentUrl	= AgentUrl;
    mCmTrigger.TraderUrl	= TraderURL;
    mCmTrigger.PackageName = id;
    mCmTrigger.PriceCurrency = PriceCurrency;
  }

  // call method
  var price="";
  mCmTrigger.GetPriceOffer();
  
  GetLastErr();
  if ( lastErr != 0 )
  {
    //alert(lastErrMsg+" (Errorcode: "+lastErr+")");
  } 

  //program FSB
  mCmTrigger.SetCreditCardData("VISA",	"4444333322221111", "1234567", 1 & 0xffff, 2011 & 0xffff)
  mCmTrigger.GetBoxUpdate();
  if ( mCmTrigger.LastErrorCode != 0 ) {
  	if(iteration<4) {
  		iteration++;
  		UpdateUnitCounter(id);
  		//alert("Kommunikation mit Codemeter-Server fehlgeschlagen - Starte Versuch "+iteration);
  	} else {
        //alert("redirect error");
    	window.location='/codemetererror.php';
    	return false;
    }
  } else {
      //alert("update ok");
    if(id!=6666) alert("Guthaben wurde aktualisiert!");
    return true;
  } // if/else
  return false;  
} // updateUnitCounter()

function onLoadSelectStick()
{ 
  	InsertObject();
    if(mCmTrigger==null) return;
    if (IsApplet)
    	window.setTimeout("InitBoxes()",timeout);
  	else
  		try {
        	InitBoxes();
        } catch (Exception) {
        	document.getElementById("activexmessage").innerHTML="<img src=\"../img/activex_message.gif\" width=\"1000\" height=\"37\"><br />&nbsp;";
        	//alert("Hinweis: Das Add-On zur Erkennung des Guthaben-Sticks konnte nicht ausgeführt werden.\nEntweder haben Sie keine Codemeter-Software installiert, oder Ihr Webbrowser verhindert den Start des Add-Ons.\nBitte erlauben Sie in diesem Fall die Funktion durch Anklicken des gelben Balkens am Kopf Ihres Browsers!");
        }
}

function InsertObject()
{
    var target=document.getElementById("WIBU");
	if(getCookie("type")==null || getCookie("type")==1) {
		//get ActiveX
		try {
			var object=document.createElement("Object");
			object.setAttribute("id","mCmTrigger");
			object.setAttribute("classid","clsid:00040000-0000-1011-8005-0000C06B5161");
			target.appendChild(object);
	    } catch (Exception) {}
		if(mCmTrigger!=null) { 
			//has ActiveX
            setCookie("type",1);
  			IsApplet=false;
	  		return;
	  	}
	}
	
	if(getCookie("type")==null || getCookie("type")==2) {
		//check/get Java-Applet	
		try {
			var object=document.createElement("Applet");
			object.setAttribute("id","mCmTrigger");
			object.setAttribute("height","100");
			object.setAttribute("width","400");
			object.setAttribute("code","com.wibu.cm.Trigger.class");
			object.setAttribute("name","mCmApplet");
			object.setAttribute("scriptable","true");
			var param=document.createElement("PARAM");
			param.setAttribute("Name","traderurl");
			param.setAttribute("Value",TraderURL);
			object.appendChild(param);
			target.appendChild(object);	
	    } catch (Exception) {}
	
		if(mCmTrigger!=null) { 
			//has ActiveX
	  		setCookie("type",2);
  			IsApplet=true;
	  		return;
	  	}
	}
	//no ActiveX and Java-Applet
	document.getElementById ("noPlugin").style.visibility = "visible";
    document.getElementById ("check").style.visibility = "hidden";

}

function testUnitCounter() {
    var success = UpdateUnitCounter(6666);
    if(!success) return false;
    document.shoppingcart.testupload.value="true";
    document.shoppingcart.submit();
}

function hasFlashPlugin() {
    // Netscape style plugin detection
    if (navigator.plugins && navigator.plugins.length) {
        for (x = 0; x <navigator.plugins.length; x++) {
            if (navigator.plugins[x].name.indexOf('Shockwave Flash') != -1) {
                return true;
            }
        }
    }

    // ActiveX style plugin detection
    else if (window.ActiveXObject) {
        var flash_versions = 10;
        for (x = 2; x <= flash_versions; x++) {
            try {
                oFlash = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + x + "');");
                if (oFlash) {
                    return true;
                }
            }
            catch(e) { }
        }
    }
    return false;
}

function ebookOverlay(visibility, link) {
    try {
        var softenBackgroundStyle = document.getElementById('softenBackground').style;
        softenBackgroundStyle.height = "1600px";
        softenBackgroundStyle.visibility = visibility;
        document.getElementById('ebookLink').innerHTML = "<a href=\""+link+"\" target=\"_blank\" class=\"linkb\">Zu Ciando</a>";
        document.getElementById('ebookOverlay').style.visibility = visibility;
    } catch(e) { }
}

