var preloadFlag = false;
var preloadStack = new Array("preloadImages();","textOnly(false);");
var pgPreloadImage = new Array();

function newImage(arg) {
	if (document.images) {
		rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
}

function changeImages() {
	if (document.images && (preloadFlag == true)) {
		for (var i=0; i<changeImages.arguments.length; i+=2) {
			document.getElementById(changeImages.arguments[i]).src = changeImages.arguments[i+1];
		}
	}
}

function preloader()
{
	for(j=0; j < preloadStack.length; j++)
	{
		eval(preloadStack[j]);
	}
}

function preloadImages() {
	if (document.images) {
		for(x=0;x<pgPreloadImage.length;x++){
			eval("pgPreloadImage"+x+"=newImage('"+pgPreloadImage[x]+"');");
		}
		preloadFlag = true;
	}
}

function preloadImage(imageUrl)
{
	pgPreloadImage[pgPreloadImage.length] = imageUrl;
}

function addToOnload(js)
{
	preloadStack[preloadStack.length] = js;
}


//
// Text only mode
//
function textOnly(flip)
{

	if (flip)
		textOnlyState = (getCookie("textOnly") == 1) ? false : true;
	else
		textOnlyState = (getCookie("textOnly") == 1) ? true : false;

	try
	{
		stylesheets=this.document.styleSheets;
		for( i=0; i < stylesheets.length; i++)
		{
			stylesheets[i].disabled = textOnlyState;
		}
		setCookie('textOnly',(textOnlyState) ? 1:0,365, '/', '', '');
		document.getElementById('textOnlyLink').innerHTML = (textOnlyState) ? "Full graphics site" : "Text only";
	}
	catch(e){
	}
}



function textboxFocus(obj,defaultVal)
{
	if(obj.value==defaultVal)
	{
		obj.value='';
		obj.style.color='#000';
	}
}

function textboxBlur(obj,defaultVal)
{
	if(obj.value=='')
	{
		obj.value=defaultVal;
		obj.style.color='#999';
	}
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.com
// Edit for Firefox by pHaez
//
function getPageSize(){

    var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;

//    console.log(self.innerWidth);
//    console.log(document.documentElement.clientWidth);

    if (self.innerHeight) {    // all except Explorer
        if(document.documentElement.clientWidth){
            windowWidth = document.documentElement.clientWidth;
        } else {
            windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }

//    console.log("xScroll " + xScroll)
//    console.log("windowWidth " + windowWidth)

    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){
        pageWidth = xScroll;
    } else {
        pageWidth = windowWidth;
    }
//    console.log("pageWidth " + pageWidth)

    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
    return arrayPageSize;
}


function CloseWindow(){
		removeEcard();
}

function previewEcard( code,nameID,messageID,xmasID,orderID,itemValue )
{
    var name = document.getElementById(nameID);
		var message = document.getElementById(messageID);
    var xmasRadio = document.getElementsByName(xmasID);
    var flexible = 0;
    var xmas = 0;

    if ( code == 'ZA' || code == 'ZB' || code == 'ZC' || code == 'ZD' )
    {
    	flexible = 1;
    }

    for(i = 0 ; i < xmasRadio.length ; i++)
    {
      if (xmasRadio[i].checked)
      {
        var xmas = xmasRadio[i].value;
      }
    }

	viewEcard( code,name.value,message.value,0,0,xmas,flexible,orderID,itemValue )
}

function previewCorpEcard( code,companyID,messageID,orderID,contactName )
{
    var company = document.getElementById(companyID);
    var contactName= document.getElementById(contactName);
		var message = document.getElementById(messageID);
    var flexible = 0;
    var corp = 1;
    
		viewEcard( code,company.value,message.value,0,0,corp,flexible,orderID,contactName.value )
}


function viewEcard(code,name,message,preview,seeFlash,corp,flexible,orderID,itemValue)
{

    if(name == "" && preview == 1 )
    {
        name = "Claire";
    }

    if(message == "" && preview == 1 )
    {
        message = "I hope you like the present. \r\nDavid.";
    }

    message = unescape(message);
    var html;
    var arrayPageSize = getPageSize();

    nx = "";
    linkText = "Click here to view the E-Card";
    linkFlag = "0";


	xmasOption = '';

    var flashinstalled = 0;
    var flashversion = 0;
    if (navigator.plugins && navigator.plugins.length)
    {
        x = navigator.plugins["Shockwave Flash"];
        if (x)
        {
            flashinstalled = 2;
            if (x.description)
            {
                y = x.description;
                flashversion = y.charAt(y.indexOf('.')-1);
            }
        }
        else
            flashinstalled = 1;
        if (navigator.plugins["Shockwave Flash 2.0"])
        {
            flashinstalled = 2;
            flashversion = 2;
        }
    }
    else if (navigator.mimeTypes && navigator.mimeTypes.length)
    {
        x = navigator.mimeTypes['application/x-shockwave-flash'];
        if (x && x.enabledPlugin)
            flashinstalled = 2;
        else
            flashinstalled = 1;
    }
    else
    {
        // IE flash detection.
        for(var i=9; i>0; i--){
            flashversion = 0;
            try{
                var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
                flashversion = i;
                break;
            }
            catch(e){
            }
        }
        if(flashversion > 0)
        {
            flashinstalled = 2;
        }
        else
        {
            flashinstalled = 0;
        }
    }


    hideSelects();
	cardContainer = document.createElement("div");
	cardContainer.id  = "ecardOverlay";
	cardContainer.style.height =  arrayPageSize[1] + "px";
	cardContainer.style.width =  arrayPageSize[0] + "px";
	cardContainer.style.top = "0px";

	document.body.appendChild(cardContainer);
	cardContainerInner = document.createElement("div");
	cardContainerInner.id  = "ecardOverlayInner";
	cardContainerInner.style.width =  document.body.clientWidth + "px";
	cardContainerInner.style.top = scrollPos()+"px";

    if (seeFlash == 1 && flashinstalled == 2 && flexible != 1 )
    {
			var theMessage = escape( message );
			theMessage = theMessage.replace( /%0D/g, '' );
			displayMode = "flash";
			html = '<table height="100%" width="100%" border="2"><tr><td style="text-align:center"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="https://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="700" height="445" id="ecard" align="middle">';
			html += '<param name="allowScriptAccess" value="sameDomain" />';
			html += '<param name="movie" value="/flash/ecards/' + nx + 'ecard.swf?sample=' + code + '&preview=' + 1 + '&toName=' + name + '&toMessage=' + theMessage + '" />';
			html += '<param name="quality" value="high" />';
			html += '<param name="bgcolor" value="#ffffff" />';
			html += '<embed src="/flash/ecards/' + nx + 'ecard.swf?sample=' + code + '&preview=' + 1 + '&toName=' + name + '&toMessage=' + theMessage + '" quality="high" bgcolor="#ffffff" width="700" height="445" name="ecard" align="middle" style="vertical-align:middle;" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="https://www.macromedia.com/go/getflashplayer" />';
			html += '</object>';
      html += '<div style="background-color: white; margin: 0 auto; width: 700px; text-align: center;"><small style="padding: 5px;"><a href="#" onclick=\'removeEcard(); viewEcard("' + code + '", "' + name + '", "' + theMessage + '", "' + preview + '", "' + 0 + '", "' + xmas + '"); return false;\' title="View HTML E-Card">Having problems viewing this E-Card? Click here to view the HTML version</a><br />' + xmasOption + '</small></div>';
      html += '</td></tr></table>';

      cardContainerInner.innerHTML = html;

       document.body.appendChild(cardContainerInner);

        return false;
	}
	else
    {


    var request = createXMLHttpRequest();
    message = message.replace('&', '%26');
    name = name.replace('&', '%26');

    if ( corp == 1 )
    {
        request.open("GET", "/htmlECardCorp.inc.php?sample="+ code + "&name=" + name + "&message=" + message + "&view=" + preview + "&flexible=" + flexible + "&o=" + orderID + "&value=" + itemValue, true);
    }
    else
    {
        request.open("GET", "/htmlECard.inc.php?sample="+ code + "&name=" + name + "&message=" + message + "&view=" + preview + "&flexible=" + flexible + "&o=" + orderID + "&value=" + itemValue, true);
    }

    request.onreadystatechange = function()
    {
        if (request.readyState == 4)
        {
            html = request.responseText;

            cardContainerInner.innerHTML = html;

            document.body.appendChild(cardContainerInner);
            return false;
        }
    }
    request.send(null);
	}
}




function viewPostalCard(code,Image,noun)
{
    var html;
    var arrayPageSize = getPageSize();



  hideSelects();
	cardContainer = document.createElement("div");
	cardContainer.id  = "ecardOverlay";
	cardContainer.style.height =  arrayPageSize[1] + "px";
	cardContainer.style.width =  arrayPageSize[0] + "px";
	cardContainer.style.top = "0px";

	document.body.appendChild(cardContainer);
	cardContainerInner = document.createElement("div");
	cardContainerInner.id  = "ecardOverlayInner";
	cardContainerInner.style.width =  document.body.clientWidth + "px";
	cardContainerInner.style.top = scrollPos()+"px";

  var request = createXMLHttpRequest();
 	request.open( "GET", "/postal-preview.php?noun=" + noun +"&sample="+ code +"&image="+ Image, true );
  request.onreadystatechange = function()
  {
      if ( request.readyState == 4 )
      {
          html = request.responseText;

          cardContainerInner.innerHTML = html;

          document.body.appendChild( cardContainerInner );
          return false;
      }
  }
  request.send( null );

}



function removeEcard()
{
	cardContainerInner = document.getElementById('ecardOverlayInner');
	cardContainer = document.getElementById('ecardOverlay');

	cardContainerInner.innerHTML = '';
	cardContainer.innerHTML = '';
	document.body.removeChild(cardContainerInner);
	document.body.removeChild(cardContainer);
	showSelects()
}

function turnCard()
{


	if ( document.getElementById ('ecard-front').style.display == "none" )
	{
		//front.style.display = "block";
		//back.style.display = "none";
		CrossFade ( 'back','front' );
	}
	else
	{
		//front.style.display = "none";
		//back.style.display = "block";
		CrossFade ( 'front','back' );
	}


}

var fadeOpacity = 0;
var fadeTimer;


function CrossFade(fromID, toID)
{
	toDiv = document.getElementById ('ecard-' + toID );
	fromDiv = document.getElementById ('ecard-' + fromID );
    if (fadeOpacity == 0) toDiv.style.display = "block";

	fadeOpacity += 10;

    changeOpacity(fadeOpacity, toDiv);
	changeOpacity(100 - fadeOpacity, fromDiv)
	if(fadeOpacity < 100)
	{
		fadeTimer = setTimeout('CrossFade("'+fromID+'", "'+toID+'")', 100);
	}
	else
	{
		clearOpacity(toDiv);
		fromDiv.style.display = "none";
		changeOpacity(100, fromDiv);
	}
}

function changeOpacity(opacity, object) {
object.style.opacity = (opacity / 100);
object.style.MozOpacity = (opacity / 100);
object.style.KhtmlOpacity = (opacity / 100);
object.style.filter = "alpha(opacity=" + opacity + ")";
}

function clearOpacity(object) {
object.style.opacity = 100;
object.style.MozOpacity = 100;
object.style.KhtmlOpacity = 100;
object.style.filter = "";
fadeOpacity = 0;
}

function hideSelects()
{
	selects = document.getElementsByTagName("select");
	for (j=0; j<selects.length; j++)
	{
		selects[j].style.visibility = 'hidden';
	}
}

function showSelects()
{
	selects = document.getElementsByTagName("select");
	for (j=0; j<selects.length; j++)
	{
		selects[j].style.visibility = 'visible';
	}
}

function scrollPos()
{
	if (window.pageYOffset)
	{
		return window.pageYOffset
	}
	else if (document.documentElement && document.documentElement.scrollTop)
	{
		return document.documentElement.scrollTop
	}
	else if (document.body)
	{
		return document.body.scrollTop
	}
	else {
		return 0;
	}
}


//
// Cookie Handling functions
//

function setCookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// this function gets the cookie, if it exists
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )
	{
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function deleteCookie( name, path, domain ) {
	if ( Get_Cookie( name ) )
		document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function createXMLHttpRequest() {
    if (typeof XMLHttpRequest != "undefined") {
        return new XMLHttpRequest();
    } else if (typeof ActiveXObject != "undefined") {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        throw new Error("XMLHttpRequest not supported");
    }
}
