//////////////////////////
// Declarations variables:

//var vHttp = getHttpRequest();

// MANAGER PHP SCRIPT
var vURL = "common_cart.php";

// ZONES -------------
var vDisplayZone = new Object();
function initZones() {
	var information = document.getElementById( "information" );
	var software = document.getElementById( "list" );
	var subCart = document.getElementById( "subCartHome" );
	var categories = document.getElementById( "categories" );
	
	vDisplayZone["SOFT_DETAILS"] = information;
	vDisplayZone["SOFT_LIST"] = software;
	vDisplayZone["CART"] = subCart;
	vDisplayZone["CATEGORIES"] = categories;
}

var STAGES = null;
var REBATES = null;

var REBATE = 0;
var CURRENCY = "USD";

var CURRENT_CATEGORY = -1;

// END declaration variables
//////////////////////////

// GENERAL functions:
function getInitInformation() {
	var params = "operation=getInitInformation";
	ajaxRequest(params, false);
}

// DOM functions
function viewCategories() {
	var params = "operation=viewCategories&currency="+currencyForAjaxRequest( CURRENCY );
	ajaxRequest(params, false);
}

function viewListSoftware(categoryId) {
	updateTabSelection(false);
	CURRENT_CATEGORY = categoryId;
	var params = "operation=viewListSoftware&categoryId="+categoryId;
	ajaxRequest(params, false);
	updateTabSelection(true);
}

function viewSoftwareDetails(softwareId) {
	var params = "operation=viewSoftware&softwareId="+softwareId;
	ajaxRequest(params, false);
}

// Cart functions:
function addToCart( softwareId ) {
	var params = "operation=addToCart&softwareId="+softwareId;
	ajaxRequest(params,false);//true);
}

function removeToCart( softwareId ) {
	var params = "operation=removeToCart&softwareId="+softwareId;
	ajaxRequest(params,false);//true);
}

function getCart() {
	var params = "operation=getCart&currency="+currencyForAjaxRequest( CURRENCY );
	ajaxRequest(params, false);
}


// general functions:
/*
	Display zone with @content
	@displayZone:
		- SOFT_DETAILS
		- SOFT_LIST
		- CART
		- CATEGORIES

*/
function updateTabSelection(inStatus){
	if (CURRENT_CATEGORY != -1){
   		var vElemTxt = document.getElementById("tabUnSelected"+CURRENT_CATEGORY);
   		var vElemImg = document.getElementById("cat"+CURRENT_CATEGORY);
   		if (vElemTxt && vElemImg){
	   		if (inStatus == true){
	   			vElemTxt.style.color = "#86b201";
	   			vElemImg.style.zIndex = 1;
	   			vElemImg.onmouseover = function(){
	   				vElemTxt.style.color = "#86b201";
	   			};
	   			vElemImg.onmouseout = function(){
	   				vElemTxt.style.color = "86b201";
	   			};
	   		}
	   		else{
	   			vElemTxt.style.color = "black";
	   			vElemImg.style.zIndex = "";
	   			
	   			vElemImg.onmouseover = function(){
	   				vElemTxt.style.color = "#a0b601";
	   			};
	   			vElemImg.onmouseout = function(){
	   				vElemTxt.style.color = "black";
	   			};
	   		}
	   	}
	 }
					
}

function displayZoneFromAjaxRequest(displayZone,content) {

	var zoneContainer = vDisplayZone[ displayZone ];
	if( zoneContainer ) {
		switch( displayZone ) {
			case "SOFT_DETAILS":
				// init variables				
				var softInfos = content.split( ">" );
				var id = softInfos[0];
				var name = softInfos[1];
				var description	= softInfos[2];
				var systemRequirement = softInfos[3];
				var homePage = softInfos[4];
				var downloadPage = softInfos[5];
				// --------------
				
				// empty container:
				zoneContainer.innerHTML = "";
				
				var url = "../images/" + id + "/" + id + "_icone.jpg";
				var productIcon = getIconContainer( url, "productIcon" );
				zoneContainer.appendChild( productIcon );
				
				/*
				url = "images/" + id + "/" + id + "_1.jpg";
				var productSS = getIconContainer( url, "productSS" );
				zoneContainer.appendChild( productSS );
				*/
				url = "../images/" + id + "/" + id + "_1.jpg";
				var preview = document.getElementById( "preview" );
				preview.innerHTML = "<img src='"+url+"' alt='preview'></img>";
								
				var element = document.createElement( "div" );
				element.className = 'productTitle';
				element.innerHTML = name;
				zoneContainer.appendChild( element );
				
				element = element.cloneNode( false );
				element.className = 'productDesc';
				element.innerHTML = description;
				zoneContainer.appendChild( element );
				
				element = element.cloneNode( false );
				element.className = 'productConfig';
				element.innerHTML = systemRequirement;
				zoneContainer.appendChild( element );
				
				element = element.cloneNode( false );
				element.className = 'productBtMI';
				element.innerHTML = "<a style='color:yellow' target=new_window href='"+homePage+"'>learn more...</a>";
				zoneContainer.appendChild( element );			
				
				element = element.cloneNode( false );
				element.className = 'productBtDL';
				element.innerHTML = "<a style='color:yellow' target=new_window href='"+downloadPage+"'>download</a>";
				
				zoneContainer.appendChild( element );
			
			break;
			
			case "SOFT_LIST":

				zoneContainer.innerHTML = "";
				var table = document.createElement( "table" );
				var tbody = document.createElement( "tbody" );
				
				// European edition
				if (CURRENT_CATEGORY == 70){
					var line = document.createElement( "tr" );
					var softName = document.createElement( "td" );
					softName.className = "comments";
					softName.innerHTML = "Missed the first promo?";
					softName.innerHTML += "<br>You can still enjoy FIXED discounts on a selection of apps.";
					softName.colSpan=4;
					line.appendChild( softName );
					tbody.appendChild( line );	
				}
				//alert( content );
				if( content.length > 0 ) {
					var softs = content.split("|");
					for( var i=0;i<softs.length;i++ ) {				
						
						var soft = softs[i].split( ">" );
						var id = soft[0];
						var name = soft[1];
						updateCurrency( soft[2] );
						var amount = soft[3];
					
						var line = document.createElement( "tr" );
						line.className = "product";
						line.setAttribute( "onclick", "javascript:viewSoftwareDetails( "+id+" );");
										
						// ICON
						var softIcon = document.createElement( "td" );
						var urlImg = "../images/"+id+"/"+id+"_icone.jpg";
						softIcon.innerHTML = "<img src='" + urlImg + "' alt='" + name + "'></img>"
						line.appendChild( softIcon );
						
						// NAME
						var softName = document.createElement( "td" );
						softName.className = "name";
						softName.innerHTML = name;
						line.appendChild( softName );
						
						
						// AMOUNT
						var softPrice = document.createElement( "td" );
						softPrice.className = "softPrice";
						softPrice.id = id;
						 
						/*
						var oldPrice = null;
						var newPrice = null;
						if( currencyT == "USD" ) {
						
							oldPrice = "$" + amount;
							newPrice = getPrice( id, REBATE, currencyT );
							
						} else {
						
							oldPrice = amount + " &euro;";
							newPrice = getPrice( id, REBATE, currencyT );
							
						}
						*/
						
						// create prices zones
						// html will be complete when totals details will be send:
						var oldPriceEl = document.createElement( "div" );
						oldPriceEl.className = "oldPrice";
					//	oldPriceEl.innerHTML = oldPrice;
						
						var actualPriceEl = document.createElement( "div" );
						actualPriceEl.className = "newPrice";
					//	actualPriceEl.innerHTML = newPrice;	
						
						softPrice.appendChild( oldPriceEl );
						softPrice.appendChild( actualPriceEl );
						
						line.appendChild( softPrice );
						
						// ADD
						var addButton = document.createElement( "td" );
						addButton.id = "bAddProd"+id;
						
						addButton.innerHTML = "<div class='plus' onclick='add_product("+id+");'></div>";
						line.appendChild( addButton );
						
						// Append line to list:					
						tbody.appendChild( line );				
					}
					table.appendChild( tbody );
					if (navigator.appName=="Microsoft Internet Explorer"){
						zoneContainer.innerHTML = "<table>"+table.innerHTML+"</table>";
					}
					else {
						zoneContainer.appendChild( table );
					}		
					updatePrices();
					updateProductListState();
				}
				
			break;
			
			case "CART":
				bundleTitle = false;
				rebateTitle = false;
				// empty zone:
				zoneContainer.innerHTML = "";
				
				// BUNDLE CART:			
				var softs = document.createElement( "div" );
				softs.className = "softs";
				var totals = document.createElement( "div" );
				
				var tableSofts = document.createElement( "table" );
				var tbodySofts = document.createElement( "tbody" );
				var tableTotals = null;
				
				// REBATE CART
				var rebateSofts = softs.cloneNode( false );
				var rebateTotals = totals.cloneNode( false );
				var tableRebateSofts = document.createElement( "tbody" );
				var tbodyRebateSofts = document.createElement( "tbody" );
				var divRebateTotals = null;
				
				if( content.length > 0 ) {	
				
					var theCart = content.split("|");
					for( var i=0;i<theCart.length;i++ ) {
						var details = theCart[i].split(">>");
						
						if( details[0] == "HIDDEN" ) {
						
							var hiddenForm = document.getElementById( "hiddenForm" );
							hiddenForm.innerHTML = details[1];
								
						} else if( details[0] == "TOTALS" ) {
							// total details:
							// update common information:
							
							var cartNature = details[1];
							if( cartNature == "BUNDLE" ) {
								// update common information:
								updateCurrency( details[8] );
								REBATE = details[4];
								tableTotals = getDOMBundleCartTotals(details[2], details[3], details[4], details[5],details[6], details[7], details[8] );
								totals.className = "totals";
								totals.appendChild( tableTotals );
							
							} else if( cartNature == "REBATE" ) {
								// TODO, constructs the total 'rebate' cart:
								divRebateTotals = getDOMRebateCartTotals( details[2], details[3] );
								rebateTotals.appendChild(divRebateTotals);
							} else if( cartNature == "GLOBAL" ) {
								// the global total:
							//	alert( details[2]+" "+details[3]);

								updateGlobalTotal( details[2], CURRENCY );
									
							}
							
						} else {
							///////////////////////
							// LIST OF SOFTWARES //
							///////////////////////
						
							// FROM ? > id > name > qty > currency > amount
							var cartNature = details[0];
							if( cartNature == "BUNDLE" ) {
								checkAndAddBundleTitle( tbodySofts );
								var line = getDOMBundleCartSoftware(details[1],details[2],details[3],details[4],details[5], true );					
								tbodySofts.appendChild( line );
									
								//update add button in soft list:
								hideAddButton( details[1] );
								
							} else if( cartNature == "REBATE" ) {
								checkAndAddRebateTitle( tbodyRebateSofts );
								// TODO, constructs the 'rebate' cart:
								//var line = getDOMRebateCartSoftware(details[1],details[2],details[3],details[4],details[5] );
								var line = getDOMRebateCartSoftware(details[1],details[2],details[3],details[4],details[5], true );					
								tbodyRebateSofts.appendChild( line );
							}
						}
					}
				} else {
					updateGlobalTotal( 0, CURRENCY );
				}
				// finalize:
				
				tableSofts.appendChild( tbodySofts );
				softs.appendChild( tableSofts );			
				
				//tableRebateSofts.appendChild( rebateTotals );
				
				tableRebateSofts.appendChild( tbodyRebateSofts );
				rebateSofts.appendChild( tableRebateSofts );
				zoneContainer.appendChild( softs );
				zoneContainer.appendChild( totals );
				zoneContainer.appendChild( rebateSofts );			
				zoneContainer.appendChild( rebateTotals );
				// UPDATE PRICES ON LIST:				
				updatePrices();
				updateProductListState();
				
				
			break;
			
			case "CATEGORIES":
				zoneContainer.innerHTML = "";
				
				var categories = content.split( "|" );
				for( var i=0;i<categories.length;i++ ) {
					//categories
					var categorie = categories[i].split("@");
					var id = categorie[0];
					var name = categorie[1];
					var selected = categorie[2];
					
					// get back the categorie state 
					
					var cat = document.createElement( "div" );

				/*	if( categorie[2] && categorie[2] == "SELECTED" ) {
						cat.className = "selected";
						// show category content:
						viewListSoftware(id);
					} */
					cat.id="cat"+id;
			
					
				//	url = "../images/cat" + id +".png";
					cat.innerHTML = "<span id='tabUnSelected"+id+"' onclick='viewListSoftware("+id+")'>"+ name +"</span>";
					
					//cat.setAttribute( "onclick","viewListSoftware("+id+")" );
					
					zoneContainer.appendChild( cat );
				}
				
			break;
			
		}
	} else {
		if( displayZone == "STAGES" ) {
		
			// 107 > O:16.80:25.00 > 30:11.76:17.50 > 40:10.08:15.00>50:8.40:12.50 > 70:5.04:7.50
			STAGES = new Array();	
			
			var softs = content.split( "|" );
			for( var i=0;i<softs.length;i++ ) {

				var stages = softs[i].split( ">" );
				var softId = stages[0];
				
				if( stages[1] == "BUNDLE" ) {					
					
					STAGES[softId] = new Object();
					for( var j=2;j<stages.length;j++ ) {
						// prices for stage
						var details = stages[j].split( ":" );
						
						STAGES[softId].nature = "BUNDLE";
						STAGES[softId][details[0]] = new Object();
						STAGES[softId][details[0]].euro = details[1];
						STAGES[softId][details[0]].dollar = details[2];
					}
					
				} else if( stages[1] == "REBATE" ) {
				
					STAGES[softId] = new Object();
					// prices for stage
					var details = stages[2].split( ":" );
					
					
					STAGES[softId].nature = "REBATE";
					STAGES[softId].euro = details[0];
					STAGES[softId].dollar = details[1];
					STAGES[softId].euroOR = details[2];
					STAGES[softId].dollarOR = details[3];
				
				}
			}			
		}
	
	}
	
}



function updateGlobalTotal( newTotal, currency ) {
	var globalTotal = document.getElementById( "globalTotal" );
	//globalTotal.className = "totals";
	if( Number( newTotal ) > 0 ) {
		/// GGF2: "GRAND TOTAL: "
		globalTotal.innerHTML = "TOTAL: " + formatPrice( newTotal, currency );
	} else {
		globalTotal.innerHTML = "TOTAL: " + formatPrice( 0, currency );
	}
}

function updatePrices() {	
	
	var currency = CURRENCY;
	var rebate = REBATE;

	//alert( rebate +":"+ currency );
	var listOftProducts = document.getElementById( "list" );
	var lines = listOftProducts.getElementsByTagName( "tr" );
	for( var i=0;i<lines.length;i++ ) {
		var tdInLine = lines[i].getElementsByTagName( "td" );
		var softPrices = null;
		for( var j=0;j<tdInLine.length;j++ ) {
			if( tdInLine[j].className == "softPrice" ) {
				softPrices = tdInLine[j];
				//break;
			}
			
			if( softPrices ) {
				var softId = softPrices.id;
				if( softId > 0 ) {
					var divs = softPrices.getElementsByTagName( "div" );
					var oldPrice = divs[0]
					var newPrice = divs[1];
					
					updatePrice( oldPrice, newPrice, softId, rebate, currency);
				}
			}		
		}
	}
}

function updateCurrency( newCurrency ) {
	CURRENCY = newCurrency;
	var currencyChooser = document.getElementById("currencyChooser"); 
	if( CURRENCY == "USD" ) {
		if( currencyChooser ) {
			currencyChooser.className = "dollar";
		}
	} else {
		// euro
		if( currencyChooser ) {
			currencyChooser.className = "euro";
		}
	}
}


/* 
	@rebate: percent rebate
	@currency : euro, dollar or USD, EUR
*/
function updatePrice( oldPrice, newPrice, softId, rebate, currency ) {
	if( !STAGES ) {
		getInitInformation();
	}
	
	if( !rebate ) {
		rebate = 0;
	}
	
	if( currency == "USD" ) currency = "dollar";
	else if( currency == "EUR" ) currency = "euro";
	else currency = "dollar";
	
	// get back details for soft:
	
	var natureOfSoft = STAGES[softId].nature;
	
	//////////
	// BUNDLE
	if( natureOfSoft == "BUNDLE" ) {
	
		var normalPrices = STAGES[softId][ 0 ];
		var rebates = STAGES[softId][ rebate ];
		if( rebates ) {	
					
			if( rebate > 0 ) {
				oldPrice.innerHTML = formatPrice( normalPrices[ currency ], currency );
			} else {
				oldPrice.innerHTML = "";
			}
			newPrice.innerHTML = formatPrice( rebates[ currency ], currency );
		} else {
			//alert( " softId: "+softId+"; ST: "+STAGES[softId][ rebate ]+"; Rebate: "+rebate );
			return 0;
		}
		
	//////////
	// REBATE	
	} else if ( natureOfSoft == "REBATE" ) {
		var prices = STAGES[softId];
		//alert( formatPrice( prices[ currency+"WR" ], currency ) );
		
		oldPrice.innerHTML = formatPrice( prices[ currency+"OR" ], currency );
		newPrice.innerHTML = formatPrice( prices[ currency ], currency );
	}
}

function getIconContainer( url, className ) {
	var iconContainer = document.createElement( "div" );
	iconContainer.className = className;
	var img = document.createElement( "img" );
	img.src = url;
	img.width = 50;
	img.height = 50;
	iconContainer.appendChild( img );
	return iconContainer;
}

// send post request and get back needed information:
function ajaxRequest( params, asynchronous ) {

	var http = getHttpRequest();
	//var http = vHttp;
	
	if( params == null || params == "" ) params = "";
	else params = "?" + params;

	http.open("GET", vURL+params, asynchronous);
	http.send(null);
	var response = http.responseText.split( "|" );
	var result = response[0]; // OK or ER
	if( result == "OK" ) {
		var displayZone = response[1];
		// reconstruct the response, 
		// remove the header information
		var header = "OK|"+displayZone+"|";
		var headerLength = header.length;
		var content = http.responseText.substr(headerLength);
		
		displayZoneFromAjaxRequest(displayZone,content);
	} else {
		//alert( "Ajax request: return error" );
	}
	
}
// functions: buySoftware, dec_software ??