var ITEMS_PER_PAGE = 12, TABLE_ON = 0,	ITEMS, CATEGORY, CUSTOMIZE, CASHNAME;


function mupimp(data) {
   if(data==null)
	alert('error');
  else  { 	 
	var x = data.data;
	var tr = $('shopcontent').empty();
	var head = new Element('h2').inject(tr);

	var ul = new Element('ul').inject(tr);

	var count = 0;
			x.each(function(i) { 
			 if (i.name) {
			 count++;
				var li = new Element('li');
				var pic = new Element('div',{'class':'img'}).injectInside(li);
					var img = new Element('img',{'src':site.template+'pages/webshop/items/'+i.img}).injectInside(pic);
				var h3 = new Element('h3').set('html',i.name).injectInside(li);
				var info = new Element('div',{'class':'info'}).set('html','Base Price: <b>'+i.credits+'</b>').injectAfter(h3);
				li.addEvent('click',function() {
					addScript(site.cache+site.location+'mupimp.php?callback=customize&id='+i.uid+'&type=json');
				});
				li.inject(ul);
			}
			});
	head.set('html', 'There is <b>'+count+'</b> items on <i><b>'+site.shopcat);
		
  }
}
function customize(data) { 
    var tr = $('shopcontent').empty();  
    var i = data.CUSTOM;
    var ul = new Element('ul').inject(tr);
    var li = new Element('li');

	var h3 = new Element('h3').set('html',data.NAME).inject(li);
	var pic = new Element('div',{'class':'img'}).inject(li);
	var img = new Element('img',{'src':site.template+'pages/webshop/items/'+data.IMG}).injectInside(pic);
        img.addEvent('error',function() {
                        		this.set({
						src: site.template+'pages/webshop/images/'+(data.CATEGORY.toInt()+1)+'.png',
						alt: 'Sorry!  This image is not available!'						
					});
        });

	var info = new Element('ol',{'class':'info'}).injectAfter(pic);
	var tog = new Hash({0: "Disabled",1:"Enabled"});
	var hash = new Hash({"Base Price":data.CREDITS, "Item Size": data.X +' by '+data.Y, "Has Level":tog.get(i[2]), "Max Level": i[8], "Has Option":tog.get(i[3]),"Max option": i[7], "Has Luck": tog.get(i[0]), "Has Skill": tog.get(i[1])});
	hash.each(function(value, key){
		 var li = new Element('li').set('html', key+': <b>'+value+'</b>').inject(info);
	});
	li.inject(ul);
        var lic = new Element('li',{'class':'customizer'});
        var h3 = new Element('h3',{'html':'Item Customizer'}).inject(lic);
        var form = new Element('form', {'id':'mycustom','target':'#','method':'get'}).inject(lic);
        var table = new Element('table').inject(form);
    
        //item level
        if (data.CUSTOM[2] == 1) {	
		var tr = new Element('tr').inject(table);
                var td = new Element('td',{'class':'alt3'}).inject(tr);
                var itemlevel =  new Element('td',{'class':'alt2  subtotal','html':0}).inject(tr);           
                new Element('label',{'html':'Item Level','for':'item_level'}).inject(td);
                var select = new Element('select',{'id':'item_level'}).inject(td);
                for (var ii=0;ii<=data.CUSTOM[8];ii++) 	{
			new Element('option',{'value':ii,'text':'+'+ii}).inject(select);
		}    
                select.addEvent('change',function() { 
                    itemlevel.set('html',this.value.toInt() * CUSTOMIZE.itemlvl);
                    totals();
                });
        }
        //item option
           if (data.CUSTOM[3] == 1) {	
		var tr = new Element('tr').inject(table);
                var td = new Element('td',{'class':'alt3'}).inject(tr);
                var itemoption =  new Element('td',{'class':'alt2  subtotal','html':0}).inject(tr);           
                new Element('label',{'html':'Item Option','for':'item_option'}).inject(td);
                var select = new Element('select',{'id':'item_option'}).inject(td);
                for (var ii=0;ii<=data.CUSTOM[7];ii++) 	{
			new Element('option',{'value':ii,'text':'+'+(ii*data.CUSTOM[5] )}).inject(select);
		}    
                select.addEvent('change',function() { 
                    itemoption.set('html',this.value.toInt() * CUSTOMIZE.itemopt);
                    totals();
                });
            }
         // has skill
     
           if (data.CUSTOM[1] == 1) {	
		var tr = new Element('tr').inject(table);
                var td = new Element('td',{'class':'alt3'}).inject(tr);
                var itemskill =  new Element('td',{'class':'alt2  subtotal','html':0}).inject(tr);           
                new Element('label',{'html':'Item Skill','for':'item_skill'}).inject(td);
                 var checkbox = new Element('input',{'type':'checkbox','id':'item_skill','value':1}).inject(td);
                checkbox.addEvent('click',function() { 
                    if (this.checked == true)
                        itemskill.set('html',this.value.toInt() * CUSTOMIZE.itemskill);
                    else  itemskill.set('html',0);
                    totals();
                });
            }
         // has luck
     
           if (data.CUSTOM[0] == 1) {	
		var tr = new Element('tr').inject(table);
                var td = new Element('td',{'class':'alt3'}).inject(tr);
                var itemluck =  new Element('td',{'class':'alt2  subtotal','html':0}).inject(tr);           
                new Element('label',{'html':'Item Luck','for':'item_luck'}).inject(td);
                 var checkbox = new Element('input',{'type':'checkbox','id':'item_luck','value':1}).inject(td);
                checkbox.addEvent('click',function() { 
                    if (this.checked == true)
                        itemluck.set('html',this.value.toInt() * CUSTOMIZE.itemskill);
                    else  itemluck.set('html',0);
                    totals();
                });
            }
       
        switch (data.CUSTOM[1]) {
            case 1:
                var exl = ['Increase Zen After Hunt +40%','Defense success rate +10%','Reflect damage +5%','Damage Decrease +4%','Increase MaxMana +4%','Increase MaxHP +4%'];
            break;
            case 0:
            	var exl = ['Increase MP / Kill +8','Increase HP / Kill +8','Increase Attacking(wizardly)speed+7','Increase Wizardly damage +2%','Increase Damage +level/20','Excellent Damage Rate +10%'];
            break;
            case 2:
                var exl = ['Increase HP','Increase MP','Ignore opponents defense +3%','Increase Stamina','Increase attack speed'];
            break;
			case 4: 
			  var exl = ['+115 HP','+115 MP','Ignore Enemy\'s defense 3%','+50 Max stamina','Wizardly speed +7','<i>Do not select (Gives nothing)</i>'];
			break;
			case 5: case 6:// v1
			  var exl = ['Ignore Enemy defense 5%','5% chance of reflection','5% chance of full HP Recovery','5% chance of full MP Recovery','<i>Do not select (Gives nothing)</i>','<i>Do not select (Gives nothing)</i>'];
			break;

        }
         if (exl) {
                var tr = new Element('tr').inject(table);
                var td = new Element('td',{'class':'alt3 exloptions'}).inject(tr);
                var exloption =  new Element('td',{'class':'alt2 subtotal','html':0}).inject(tr);           
                  exl.each(function(e,ee) {                 
                  var checkbox = new Element('input',{'type':'checkbox','id':'ex'+(ee+1),'value':1}).inject(td);
                  new Element('label',{'html':e,'for':'ex'+(ee+1)}).inject(td);
                  checkbox.addEvent('click',function() { 
                       var v = exloption.get('html').toInt();
                       if (this.checked == true)
                           exloption.set('html',(this.value.toInt() * CUSTOMIZE.itemexl)+v);
                        else  exloption.set('html',v-(this.value.toInt() * CUSTOMIZE.itemexl));  
                       totals();  
                  });
               });
         }
          var tr = new Element('tr').inject(table);
          var td = new Element('td',{'class':'alt1'}).inject(tr);
          var totaltd =  new Element('td',{'class':'alt2'}).inject(tr);   
          var total = new Element('div',{'html':data.CREDITS}).inject(totaltd);
          new Element('label',{'class':'total','html':'Total'}).inject(totaltd);
         var totals = function() {
           var t = data.CREDITS;
            $$('.subtotal').each(function(a) {
              t +=  a.get('html').toInt();
            });
            total.set('html',t);
        }

        var submit = new Element('input',{'type':'submit','id':'itembuyer','class':'validate[\'submit\']','value':'Buy this Item?'}).inject(td);
        new Element('label',{'html':'<b>Notice:</b> Please Logout of the Game Completely before purchasing an item.'}).inject(td);
		
	
   		var formcheck = new FormCheck(form, {
								submit:false,
								onValidateSuccess : function(){	go_pimp('ADDITEM',data.UID); }
		});
		form.addEvent('submit', function(e) { e.stop(); });
						

//login.php?&callback=mucash&do=ADDITEM&id=1762&item_level=4&item_option=2&item_luck=1&ex1=1&ex2=1&ex3=1&ex4=1&ex5=1&ex6=1
    // array(0['LUCK'],1['SKILL'],2['HASLEVEL']3['HASOPTION'],4['EXTYPE'],5['OPTIONTYPE'],6['STICKLEVEL'],7['MAXITOP'],8['MAXITLV'],9['MAXITXL']);
 //"itemexl":"150" ,"itemluck":"150" ,"itemskill":"130" ,"itemlvl":"40" ,"itemopt":"50"	x.optiontype

	lic.inject(ul);

	/* usage */
	//var chx = new IPhoneCheckboxes();
}

function intval(data) {
 return data.toInt();
}
function ADDITEM(data) {
  if(data==null)	alert('error');
  else	{ 	  
	var x = data.data;
	if (x[1].MESSAGE) { 
		
		go_login('login','do');
		notify.show({title: 'MuShop Message! ',message: x[1].MESSAGE});
	}	//$('ADDITEM').set('html',x[1].MESSAGE);

	}
	
}


function go_pimp(type,id ) {
    url = site.location + "mupimp.php?callback="+type;
	if (id >= 0 || id) url += "&id="+id;
	if (type == 'ADDITEM') {
		url = site.location + "login.php?"+site.sid+"&callback=mucash&do="+type;
		url += "&id="+id;
		$('itembuyer').style.display='none';
		if ($('item_level')) url += '&item_level='+$('item_level').options[$('item_level').selectedIndex].value
		if ($('item_option')) url += '&item_option='+$('item_option').options[$('item_option').selectedIndex].value
		if ($('item_skill')) url += '&item_skill='+($('item_skill').checked == true ? 1 : 0);
		if ($('item_luck')) url += '&item_luck='+($('item_luck').checked == true ? 1 : 0);
		if ($('ex1')) url += '&ex1='+($('ex1').checked == true ? 1 : 0);
		if ($('ex2')) url += '&ex2='+($('ex2').checked == true ? 1 : 0);
		if ($('ex3')) url += '&ex3='+($('ex3').checked == true ? 1 : 0);
		if ($('ex4')) url += '&ex4='+($('ex4').checked == true ? 1 : 0);
		if ($('ex5')) url += '&ex5='+($('ex5').checked == true ? 1 : 0);
		if ($('ex6')) url += '&ex6='+($('ex6').checked == true ? 1 : 0);
	}
	addScript(url);
	//alert(url);
}


function ShopCat(data) {
	var x = data.CatList;
	ITEMS = data.ITEMS, CATEGORY = x, CUSTOMIZE = data.CUSTOMIZER, CASHNAME = data.CASH;
	var tr =  $('shopmenu');
	var HH = new Element('div',{'class':'shopHolder'}).inject(tr);
	var imgH =  new Element('img',{'src':site.template+'pages/webshop/images/stats.png'}).injectInside(HH);
	var textH = new Element('div').set('html','Popular Items').injectAfter(imgH);
	itemSearch('all','popular');
		var ul = new Element('ul').inject(tr);
			x.each(function(i) { 
			
				var li = new Element('li');				
				var b = new Element('b',{'html':i.COUNT}).inject(li);
				var h3 = new Element('span').set('html',i.NAME).injectInside(li);
				li.addEvent('click',function() {				
					site.shopcat = i.NAME;
					itemSearch('cat',i.ID);
					this.getParent().getChildren('li').erase(this).removeClass('active');
					this.addClass('active');
					imgH.set('src',site.template+'pages/webshop/images/'+i.ID+'.png');
					textH.set('html',i.NAME);
					//navtail(i.NAME);
				});
				li.inject(ul);
				
			});

}

function itemSearch(type,id,start) {
 if (type) Cookie.write('type',type);
 else var type = Cookie.read('type');
 if (type) Cookie.write('id',id);
 else var type = Cookie.read('id');
 if (start == null) var start = 0;
 var length = ITEMS_PER_PAGE;

 if (TABLE_ON == 1) {
	  var table = new Element('table',{'id':'ItemList'}).inject($('shopcontent').empty());
	  var tr = new Element('tr').inject(table);
	  var img = new Element('th',{'class':'itemimg','html':'#'}).inject(tr);
	  var name = new Element('th',{'class':'name','html':'Item Name'}).inject(tr);
	  var credits = new Element('th',{'class':'cash','html':'Cost'}).inject(tr);
	  var buy = new Element('th',{'class':'cash','html':'Buys'}).inject(tr);
	  var th
  } else {
	 var table = new Element('ul',{'id':'ItemList'}).inject($('shopcontent').empty());
  }
 var rItems = new Hash();
 var mysort = function(a,b){
      if(a.CREDITS == b.CREDITS) return (a.NAME < b.NAME) ? -1 : 1;
	return (a.CREDITS < b.CREDITS) ? -1 : 1;
 }
    var result = ITEMS.sort(mysort);
    switch(type) {
        case 'cat':
          if (TABLE_ON == 1) var category = new Element('th',{'class':'category','html':'Info'}).inject(tr);
         var result =  ITEMS.filter(function(i,ii) {
           return i.CATEGORY == id-1
        });     
          var result = result.sort(mysort);
        break;
        case 'name':
		 if (TABLE_ON == 1) var category = new Element('th',{'class':'category','html':'Type'}).inject(tr);
           var result =  ITEMS.filter(function(i,ii) {
               return i.NAME.test(id,'i')
            });       
            var result = result.sort(mysort);
        break;
		case 'all':
           if (TABLE_ON == 1)   var category = new Element('th',{'class':'category','html':'Type'}).inject(tr);
              
             switch (id) {
                case 'popular':
                  var mysort = function(a,b){
	            if(a.PURCHASE == b.PURCHASE) return (a.NAME < b.NAME) ? -1 : 1;
	            return (a.PURCHASE > b.PURCHASE) ? -1 : 1;
                  }
                    var result = ITEMS.sort(mysort);
                break;
                case 'latest':
                 var mysort = function(a,b){
	            if(a.EDITED == b.EDITED) return (a.NAME < b.NAME) ? -1 : 1;	            
	            return (a.EDITED > b.EDITED) ? -1 : 1;
                  }
                    var result = ITEMS.sort(mysort);

                break;
              }
	  break;
    }
   var pages = (result.length / length);
   var end = (start+length);
   var presult =  result.filter(function(i,ii) {
       return ii >= start && ii < end

    });
	var fade = 350;
    presult.each(function(i,ii) {
		if (TABLE_ON == 1) {
			var tr = new Element('tr').inject(table).fade('out');
			var imgtd = new Element('td',{'class':'itemimg'}).inject(tr);
			var imgdiv = new Element('div').inject(imgtd);
			var img = new Element('img', {'class':'imgItem','src':site.template+'pages/webshop/items/'+i.IMG}).inject(imgdiv);
			var name = new Element('td',{'class':'name','title':'Customize this item before Buying','html':i.NAME}).inject(tr);
			var credits = new Element('td',{'class':'cash','html':i.CREDITS}).inject(tr);
			var buy = new Element('td',{'class':'buy','html':i.PURCHASE}).inject(tr);
			switch(type) {
				case 'cat': case 'all':
				  var category = new Element('td',{'class':'category','html':i.EDITED+'<label>Updated</label>'+i.X +' by '+ i.Y +'<label>Size</label>'}).inject(tr);
				break;
				case 'name':
					var category = new Element('td',{'class':'category','html':CATEGORY[i.CATEGORY].NAME}).inject(tr);
				break;
			}
		} else {
			var tr = new Element('li').inject(table).fade('out');
			var name = new Element('div',{'class':'name','title':'Customize this item before Buying','html':i.NAME}).inject(tr);
			var imgtd = new Element('div',{'class':'itemimg'}).inject(tr);
			var imgdiv = new Element('div').inject(imgtd);
			var img = new Element('img', {'class':'imgItem','src':site.template+'pages/webshop/items/'+i.IMG}).inject(imgdiv);
			var credits = new Element('div',{'class':'cash','html':'Starting at <b>'+i.CREDITS + '</b> ' + CASHNAME}).inject(tr);
			var buy = new Element('div',{'class':'buy','html':i.PURCHASE +' Purchases'}).inject(tr);
		
		}
		         img.addEvents({'error':function() {
                        		this.set({
						src: site.template+'pages/webshop/images/'+(i.CATEGORY.toInt()+1)+'.png',
						alt: 'Sorry!  This image is not available!'
						
					});
                                       },'mouseenter':function() {   this.addClass('active'); }
                                        ,'mouseleave':function() {   this.removeClass('active'); }
				});
		(function() { tr.fade('in'); }).delay(ii*fade);
            tr.addEvent('click', function() {
                customize(i);
            });
    });
    
    //pagination

    var ul = new Element('ol',{'class':'pagination'}).injectBefore(table);
 

    var p = [];
    var now = (start/length)+1;
  
    for (c = 1; c < pages+1; c++) { 
       if (pages > 20) {
           if (c == 1 || ( c < (now+7) && c > (now-5))) {// console.log(start / length);
             p.include(c);
        }
       } else p.include(c);
    }
   
     p.each(function(i,ii) {
       var li = new Element('li',{'html':i}).inject(ul);   
        if (i == now) li.addClass('active');      
        li.addEvent('click', function() {
           itemSearch(type,id,(i-1)*length);     
         });     
    });
	var li = new Element('li',{'class':'note','html': '<b>'+result.length+'</b> items found...'}).inject(ul);
}

function shopForm() {
	var value = $('shopSearchBox').value;
	if 	(value.length > 2 && value.length < 12) {
			   itemSearch('name',value);
				
	}
}
window.addEvent('domready', function(){

	$$('#shopSearch ul li').addEvent('click',function() {
		itemSearch('all',this.id);
	});
	$('shopSearchBtn').addEvent('click',function() {
		shopForm();
	});

		addScript('mupimp.php?callback=catFull&type=json',true);
		$('shopSearchBox').addEvents({
			'keyup': function() {

			if 	(this.value.length > 2 && this.value.length < 12) {
			   itemSearch('name',this.value);
				
			}
			}
		});

		var formcheck = new FormCheck('shopSearchForm', {
								submit:false,
								onValidateSuccess : function(){	shopForm(); }
		});
		$('shopSearchForm').addEvent('submit', function(e) { e.stop(); });
						

	

		
		
		
	 /*	$$('#shopmenu ul li').addEvents({
			'click':function() {
					var ID = this.id;
					var NAME = this.getChildren('span').get('html');
					this.getParent().getChildren('li').erase(this).removeClass('active');
					this.addClass('active');
					itemSearch('cat',this.id);
					//addScript(site.cache+site.location+'mupimp.php?callback=items&id='+ID+'&type=json');				
					site.shopcat = NAME;
					$('shopHolderImg').set('src',site.template+'pages/webshop/images/'+ID+'.png');
					$('shopHolderDiv').set('html',NAME);
					//navtail(NAME);
					//pop_min();
			},
			'mouseenter': function() { this.highlight('#90ff90','#000'); }
		});
		
		$$('#SubItemsMenu  li').addEvents({
		

			'mouseenter': function() {
				this.set('morph', {duration: 'long', transition: 'bounce:out'});
				this.morph({
					'background-color': ['#666','#121212'],
					'margin-top': [0, 2]					
				});
				this.addClass('active');
			
			},
			'mouseleave': function() {
				this.removeClass('active');

			},
			'click': function() {
				var sib = this.getParent().getChildren().erase(this);
				sib.removeClass('actived');
				this.addClass('actived');
				var submenu = $(this.id + 'ItemsWrap');
				$$('.subItem').fade('out');
				submenu.fade('in');
			}
		
		});*/
		/*
			new SlideItMoo({overallContainer: 'popItemsWrap',
							elementScrolled: 'popItems',
							thumbsContainer: 'popItems_items',		
							itemsVisible:4,
							itemsSelector: 'div.popitemsdiv',
							showControls:0,
							autoSlide: 3000,
							transition: Fx.Transitions.Bounce.easeOut,
							duration: 1800,
							direction:1}
			);
			new SlideItMoo({overallContainer: 'latestItemsWrap',
							elementScrolled: 'latestItems',
							thumbsContainer: 'latestItems_items',		
							itemsVisible:4,
							itemsSelector: 'div.latestitemsdiv',
							showControls:0,
							autoSlide: 3000,
							transition: Fx.Transitions.Bounce.easeOut,
							duration: 1800,
							direction:1}
			);
			$$('.subactive').fade('in');
		if (site.submod == "") var sd = 1;
		else {	
			addScript(site.cache+site.location+'mupimp.php?callback=customize&id='+site.submod+'&type=json');
			pop_min();
		}*/
	});
function pop_min() {
	$('SubItemsWrap').tween('height','100px');
	$$('.subItem2').each(function(c) { c.setStyle('height','98px'); });
		new SlideItMoo({overallContainer: 'popItemsWrap',
							elementScrolled: 'popItems',
							thumbsContainer: 'popItems_items',		
							itemsVisible:4,
							itemsSelector: 'div.popitemsdiv',
							showControls:0,
							autoSlide: 3000,
							transition: Fx.Transitions.Bounce.easeOut,
							duration: 1800,
							direction:1}
			);
			new SlideItMoo({overallContainer: 'latestItemsWrap',
							elementScrolled: 'latestItems',
							thumbsContainer: 'latestItems_items',		
							itemsVisible:4,
							itemsSelector: 'div.latestitemsdiv',
							showControls:0,
							autoSlide: 3000,
							transition: Fx.Transitions.Bounce.easeOut,
							duration: 1800,
							direction:1}
			);
}