var purchased = new Array();
var notEmptyCart = false;
var animateCounter =0;
window.addEvent('domready',function () {
	addCategoryEvent();
	addToggleEvent();
	setFreshCart();
	if ($('bannerContainer')) {
		inter = setInterval('animateBanner()',6000);
	}
	if ($$('.menu')) {
		$$('.menu ul').addEvent('click:relay(li)',function () {
			if (this.getProperty('title')) {
				location.href = this.getProperty('title');
			}
		});
	}
});
function progress(pos,val) {
  var url =  window.location.search;
  if (url.indexOf('&prev=') !=-1) {
	 url = url.substring(0,url.indexOf('&prev='));
	 url +='&';
  }else if(url.indexOf('&next=') !=-1) {
	url = url.substring(0,url.indexOf('&next='));
	url +='&';
  }else if (url =='') {
	  url ='?';
  }else {
	  url +='&';
  }
  location.href= pagename + url + pos +'=' + val.id;
}
function setLocales(val){
	var req = new Request({
		url:'function.php',
		method:'get',
		data:{action:'locale',value:val},
		onComplete:function () {
			window.location.reload();
		}
	}).send();
}
function payInterswitch() {
	var overDiv = new Element('div',{id:'overDiv'});
    overDiv.addClass('overdiv');
    overDiv.setStyle('opacity','0');
    overDiv.setStyle('height',window.getHeight() + 'px');
    overDiv.fade(0.5);
    $('body').adopt(overDiv);
    var container = new Element('div', {id:'container'});
    container.addClass('container');
    container.setStyle('width','520px');
    container.setStyle('top','60px');
    $('body').adopt(container);
    container.setStyle('left',window.getWidth()/2-(container.getCoordinates().width/2) + 'px');
    container.adopt(new Element('iframe',{id:'payswitch',width:'100%',height:'700',frameborder:'0',marginWidth:'0',marginHeight:'0',scrolling:'auto'}));
	var req = new Request({
		url:'function.php',
		method:'get',
		data:{action:'payInterswitch'},
		onComplete:function (responseText) {
			var urls = 'https://webpay.interswitchng.com/webpay/purchase.aspx' + responseText;
			$('payswitch').src=urls;
		    //container.adopt(new Element('iframe',{id:'payswitch',src:urls,width:'100%',height:'700',frameborder:'0',marginWidth:'0',marginHeight:'0',scrolling:'auto'}));
		}	
	}).send();
	var proceed = new Element('div',{id:'proceed'});
	proceed.setProperty('align','justify');
	proceed.addClass('cart');
	proceed.setStyle('float','right');
	proceed.innerHTML ='Proceed';
	proceed.addEvent('click',function () {
		if (this.getPrevious().contentDocument.location.href.indexOf('processOrder.php') !=-1) {
			location.href = 'processOrder.php?action=interswitch';
		}else {
			alert('Please complete the payment process first ');
		}
	});
	container.adopt(proceed);
}
function payGateway(val,val2) {
	$('panel_h1').innerHTML ='<img src="images/ajaxload.gif"/>Waiting while we process your transaction';
	var req = new Request({
		url:'processOrder.php',
		method:'get',
		data:{action:'pay',val:val},
		onComplete:function (responseText){
			$('panel_h1').innerHTML = responseText;
		}
	}).send();
}
function addCategoryEvent() {
	if ($('categoryList')) {
		$('categoryList').addEvent('mouseover:relay(li)',function () {
			this.setStyle('color','#ef980f');
		});
		$('categoryList').addEvent('mouseout:relay(li)',function () {
			this.setStyle('color','#666666');
		});
		$('categoryList').addEvent('click:relay(li)',function () {
			if (this.getProperty('title') !='General') {
				location.href=this.getProperty('longdesc')+'?category='+this.getProperty('title');
			}else {
				location.href='textbooks.php?category='+this.getProperty('title');
			} 
		});
	}
}
function fireCartEvents(val) {
		if ($('cartnotice')){
		$('cartnotice').dispose();
		}
		var icode = val.id;
		var list = $(icode).getParent().getElements('span');
		var tp = val.getCoordinates().top + val.getCoordinates().height +3;
		var lef = val.getCoordinates().left;
	if (Math.abs(list[1].innerHTML.substr(3).replace(',','')) !=0) {
		addElement(list[0].innerHTML,list[1].innerHTML.substr(3).replace(',',''),icode);
		cartNotification(tp,lef,list[0].innerHTML);
	}else {
		alert('This Item is not availble yet, Please check back later');
	}
}
function fireCartEvent2(val) {
if ($('cartnotice')){
    $('cartnotice').dispose();
}
	var icode = val.id;
	var list = val.getParent().getParent().getElements('span');
    var price = list[1].innerHTML.substr(3).replace(',','');
    if (icode =='D300') {
        var dateEnd = new Date(12,03,22);
        //alert(dateServer.valueOf());
        if (dateEnd.valueOf() > dateServer.valueOf()) {
            price = '69000.00';
        }
    }
	var tp = val.getCoordinates().top + val.getCoordinates().height +3;
	var lef = val.getCoordinates().left;
	if (Math.abs(list[1].innerHTML.substr(3).replace(',','')) !=0) {
		addElement(list[0].innerHTML,price,icode);
		cartNotification(tp,lef,list[0].innerHTML);
	}else {
		alert('This Item is not availble yet, Please check back later');
	}
}
function cartNotification(tp,lef) {
	var sty ='opacity:0;filter:opacity(alpha=0),color:#000;position:absolute;background-color:#fff;top:'+tp+'px;left:'+lef+'px;border:2px solid #666;padding:3px;font-family:arial;font-size:11px;';
	var el = new Element('div',{id:'cartnotice',style:sty});
	$('body').adopt(el);
	el.fade('in');
	el.innerHTML = '<strong>Added to Cart </strong><hr size="1"><p>This item has been added to cart;</p><div><p style="float:left;margin-right:2px" class="cartNormal" onclick="this.getParent().getParent().dispose();">Shop More</p><p style="float:right" class="cartNormal" onclick="this.getParent().getParent().dispose();checkOut();"> Check Out</p></div>';
}
function checkOut(){
	var req = new Request.JSON({
			url:'function.php',
			method:'post',
			data:{action:'checkoutprep'},
			onComplete:function (objectJSON) {
				$('cartContainer').setStyle('display','none');
				if (objectJSON.userStatus =='loggedIN') {
					location.href="customer.php";
				}else {
					questionUserType();
				}
			}
	}).send();
}
function questionUserType(){
	var overDiv = new Element('div',{id:'overDiv'});
    overDiv.addClass('overdiv');
    overDiv.setStyle('opacity','0');
    overDiv.setStyle('height',window.getHeight() + 'px');
    overDiv.fade(0.5);
    $('body').adopt(overDiv);
    
    var container = new Element('div', {id:'container'});
    container.addClass('container');
    var req = new Request.HTML({
        url :'chout.php',
        update:'container'
    }).send();
    
    $('body').adopt(container);
    container.setStyle('left',window.getWidth()/2-(container.getCoordinates().width/2) + 'px');

}
function animateBanner() {
	if (animateCounter < 2) {
		animateCounter ++;
	}else {
		animateCounter = 2;
	}
	$('bannerContainer').fade('out');
	var changeIt = function () {$('bannerContainer').innerHTML ='<a href="ereader.php"><img style="border:0px" src="images/slide'+animateCounter+'.gif" width="489" height="182" /></a>';};
	changeIt.delay(600);
	var displayIt = function () {$('bannerContainer').fade('in');};
	displayIt.delay(600);
}
function setFreshCart(){
	var req = new Request.JSON({
		method:'get',
		url:'function.php',
		data:{action:'cart'},
		onComplete:function (response){
			if (response) {
				notEmptyCart = true;
				purchased=response;
				createCartTable();
				updateCartLevels();
			}
		}
	}).send();
}
function addToggleEvent(){
	var list = $$('.toggleButton');
	
	list.each(function (element){
		element.addEvent('click',function(){
			if (this.innerHTML =='- Collapse') {
				this.getParent().getNext().setStyle('display','none');
				this.innerHTML ='+ Expand';
			}else {
				this.getParent().getNext().setStyle('display','block');
				this.innerHTML ='- Collapse';
			}
		});
	});
}
function addElement(item,price,icode,weight) {
	notEmptyCart = true;
	var checked = false;
	var tbl = createCartTable();
	count = 0;
	while (count<=purchased.length -1) {
		if (purchased[count].icode == icode) {
			checked = true ;
			purchased[count].qty ++;
			qty = purchased[count].qty;
			updateCartLevels();
		}
		count ++;
	}
	if (!checked) {
		purchased.push({item:item,price:price,qty:1,icode:icode,weight:weight});
		qty= 1; 
		tbl.push([item,qty,price,'<span style="cursor:pointer" onclick="remove(this,\''+icode+'\',\'incr\')"><img src="images/incr.png" style="margin-right:3px;"/></span>'+'<span style="cursor:pointer" onclick="remove(this,\''+icode+'\',\'decr\')"><img src="images/decr.png"/></span>']);
		$('clickCartText').innerHTML = 'Cart ('+ purchased.length+' Items)';
		updatePriceLevels();
	}
	alert("Item has been added to cart");
	updatePersistentStore();
}
function updateCartLevels() {
	$('cartContents').dispose();
	var tbl = createCartTable();
	var counter = 0;
	var itemCount =0;
	var items = false;
	while (counter <= purchased.length -1) {
		if (purchased[counter].qty !=0) {
			price = new Number(purchased[counter].price.replace(',','')*purchased[counter].qty);
			tbl.push([purchased[counter].item,purchased[counter].qty,price.toFixed(2),'<span style="cursor:pointer" onclick="remove(this,\''+purchased[counter].icode+'\',\'incr\')"><img src="images/incr.png" style="margin-right:3px;"/></span>'+'<span style="cursor:pointer" onclick="remove(this,\''+purchased[counter].icode+'\',\'decr\')"><img src="images/decr.png"/></span>']);
			items = true;
			itemCount ++;
		}
		counter ++;
	}
	if (items) {
		$('clickCartText').innerHTML = 'Cart ('+ itemCount+' Items)';
		updatePriceLevels();
	}else {
		notEmptyCart = false;
		$('clickCartText').innerHTML = 'Cart (0 Items)';
		$('cartContainer').setStyle('display','none');
	}
}
function movepagecursor(val) {
	var curloc = window.location.toString();
	var scurloc = curloc.split("&");
	var counter = 0;
	curloc ='';
	while (counter <= scurloc.length-1) {
		if (scurloc[counter].indexOf('next') == -1 && scurloc[counter] !='') {
			curloc +=scurloc[counter]+'&';
		}
		counter ++;
	}
	curloc +='next=' + ((val * 25) + 1);
	location.href = curloc;
}
function updatePriceLevels(){
	var counter =0;
	var price =0;
	while (counter <= purchased.length -1) {
		price += purchased[counter].qty * purchased[counter].price.replace(',','');
		counter ++;
	}
	if ($('priceCart')) {
		$('priceCart').innerHTML = 'Total Price : ' + price.toFixed(2);
	}else {
		$('cartContainer').adopt(new Element('div',{id:'priceCart',style:'padding:5px;border:1px solid #CCC;border-bottom:0px'}));
		$('cartContainer').adopt(new Element('div',{id:'checkOut',style:'margin:2px'}));
		$('checkOut').addClass('cart');
		$('checkOut').innerHTML ='Check Out';
		$('checkOut').addEvent('click',function () {
			checkOut();
		});
		$('priceCart').innerHTML = 'Total Price : ' + price.toFixed(2);
	}
}
function remove(val,icode,pos) {
	count = 0;
	while (count<=purchased.length -1) {
		if (purchased[count].icode == icode) {
			checked = true ;
			if (pos =='incr') {
				purchased[count].qty ++;
			}else {
				purchased[count].qty --;
				if (purchased[count].qty == 0) {
					val.getParent().getParent().dispose();
				}
			}
			updateCartLevels();
			updatePriceLevels();
			updatePersistentStore();
		}
		count ++;
	}
}
function createCartTable() {
	if (!$('cartContents')) {
		var tbl = new HtmlTable({
			properties:{
				border:0,
				id:'cartContents',
				cellpadding:4,
				background:'#ccc',
				width:'100%',
				cellspacing:1
			},
			headers:['Item','Qty','Price',''],
			zebra :true
		});
		$('cartContainer').innerHTML ='';
		tbl.inject($('cartContainer'));
	}else {
		tbl = new HtmlTable($('cartContents'));
	}
	return tbl;
}
function pullCartUp() {
	if ($('popups') && $('popups').getStyle('display') =='block'){
		$('popups').setStyle('display','none');
	}
	if (notEmptyCart) {
		if ($('cartContainer').getStyle('display') =='none') {
			$('cartContainer').setStyle('display','block');
			$('cartContainer').setStyle('left',($('clickCart').getCoordinates().right-250)+'px');
		}else {
			$('cartContainer').setStyle('display','none');
		}
	}
}
function updatePersistentStore(){
	var param ='';
	var counter =0;
	while (counter <= purchased.length -1) {
		if (purchased[counter].qty !=0) {
			param +=purchased[counter].item+'~'+purchased[counter].icode +'~' + purchased[counter].qty +'~'+purchased[counter].price+'~'+purchased[counter].weight+'##';
		}
		counter ++;
	}
	var vals =param.substr(0,param.length-1);
	var req = new Request.JSON({
		method:'get',
		url:'function.php',
		data:{action:'cart',con:vals}
	}).send();
}
function applydiscount() {
	var val = $('promocode').value;
	var req = new Request({
		method:'post',
		data:{action:'discount',data:val},
		url:'function.php',
		onComplete:function (responseText) {
			alert(responseText);
			window.location.reload(true);
		}
	}).send();
}
function comingSoon(tp,lef) {
	var sty ='opacity:0;filter:opacity(alpha=0),color:#000;position:absolute;background-color:#fff;top:'+tp+'px;left:'+lef+'px;border:2px solid #666;padding:3px;font-family:arial;font-size:11px;';
	var el = new Element('div',{id:'cartnotice',style:sty});
	$('body').adopt(el);
	el.fade('in');
	var myfun = function () {
		el.fade('out');
	};
	myfun.delay(2000);
	var myfun2 = function () {
		el.dispose();
	};
	myfun2.delay(3000);
	el.innerHTML = 'This Section is coming soon !';
}
