/************************************************************************************************************
	(C) www.dhtmlgoodies.com, November 2005
	
	
	************************************************************************************************************/
	function getCookie(c_name)
	{
	 if (document.cookie.length>0)
  	  {
  	   c_start=document.cookie.indexOf(c_name + "=");
  	    if (c_start!=-1)
   	    { 
   	     c_start=c_start + c_name.length+1 ;
  	     c_end=document.cookie.indexOf(";",c_start);
   	     if (c_end==-1) c_end=document.cookie.length
  	     return unescape(document.cookie.substring(c_start,c_end));
   	    } 
 	  }
	  return ""
	}

	// FUNCTION TO DELETE A <strong class="highlight">COOKIE</strong>
	function deletecookie(name) {
		var expdate = new Date();
		expdate.setTime(expdate.getTime() - 10);
		document.cookie = name += "=; expires=" + expdate.toGMTString();
	}


       function setCookie(c_name,value,expiredays)
       {
        if(document.cookie.indexOf(c_name + "=")){deletecookie(c_name);}
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : "; expires="+exdate.toUTCString());
       }

       function addToCookie(c_name,value,expiredays)
       {
        
        var oldcookie = getCookie('shoppingpanel');

        if(oldcookie)
         {
         oldcookie += value;
         }
         else
         {
         oldcookie = value;
         }
        
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie=c_name+ "=" +escape(oldcookie)+((expiredays==null) ? "" : "; expires="+exdate.toUTCString());
       }
       
       //THIS FUNCTION CREATES AN IFRAME AND APPENDS IT TO THE BODY
       //IT IS USED FOR MISC_JS FUNCTIONS
       function makeFrame(url){ 
   		ifrm = document.createElement("IFRAME"); 
  		ifrm.setAttribute("src", url); 
  		ifrm.style.width = 0+"px"; 
  		ifrm.style.height = 0+"px"; 
  		document.body.appendChild(ifrm); 
	   } 

/*
	  var cookiearray = new Array();
	  var cookietext = "";
      var cookiecounter = 0;
      
      var cookieinfo = getCookie('shoppingpanel');
      if(cookieinfo){ 
        var panel_cookie = new Array();
       	panel_cookie = cookieinfo.split("<;>");
        for(var i=0; i<panel_cookie.length; i++){
         cookiearray[i] = new Array();
         cookiearray[i] = panel_cookie[i].split("<,>");
         cookiecounter++;
        }
        buildCookieString();
       }
      


        

        
        function populatePanel()
        {
        
          var itemarray = checkCookie();

          for(var i=0; i< (itemarray.length - 1); i++)
          {

            fillPanel(itemarray[i][0], itemarray[i][1], itemarray[i][2], itemarray[i][3], itemarray[i][4], itemarray[i][5], itemarray[i][6], itemarray[i][7]);
           
          }

        }
        
*/

        function fillPanel(id, title, price, quantity, shipping, image, ownerid, ownerpic)
        {


              var item = document.createElement('LI');
             
              item.innerHTML += "<div style='width: 82px; background: url(&quot;images/transpix2.png&quot;) repeat scroll 0% 0% transparent; border: 0px none; color: rgb(255, 255, 255); font-size: 9pt; font-family: arial;'><nobr>&nbsp;" + price + "</nobr>";
              item.innerHTML += "<div style='position: relative; z-index: 1001; left: 100px; top: -45px;border: 0px;'><a href='javascript:removeItem("+ id + "," + price + ")'><img src='images/removeimage.png' width='37' height='37' border='0'></a></div>";
              item.innerHTML += "<div style='position: relative; left: 60; top: 60; border: 0px;'><input type='hidden' name='id[]' value="+id+"><input class='cart_text' type='text' name='quantity[]' id='quantity_"+id+"' size='5' value='"+ quantity +"' onkeyup='Basket.setCount("+id+","+price+");'></div>";

              item.id = "c_" + id;
              item.className = id;
              item.style.background = "url(" + image + ") no-repeat";

     /*item.attachEvent('onmouseover',changepanelname('titlex'));*/

item.setAttribute('onmouseover', 'changepanelname(\''+ title +'\')');
item.setAttribute('onmouseout', 'changepanelname(\'Shopping Panel\')');

/*item.onmouseover=changepanelname('titlex');*/

              var tr=document.getElementById("slots");
	      var slots= tr.getElementsByTagName("ul");

               for (i=0; i<slots.length; i++) 
               {
                if (slots[i].className=='empty')
                {
                   slots[i].className='full';
                   slots[i].appendChild(item);
                   openPanel();
                   addSlot();
                   i = 1000;

                }
               }

   



        }



	function addSlot()
	{
 
          var count = getNoSlots() - 1;


          if(count - getNoItems() == 0)
          {
  	  // create a new div element
          // and give it some content

  	   newTD = document.createElement("td");
           newTD.id = "item" + count;
           newTD.className = "item";
           newTD.style.verticalAlign = "top";
           newTD.innerHTML = '<ul class="empty" id=box' + count +' > </ul>';


  	  // add the newly created element and it's content into the DOM
 	   my_div = document.getElementById("slots");
           my_div.appendChild(newTD)
	   //reactivate();

           }


          
           
	}
        function getItemsInBasket()
        {
 
	  var slots=document.getElementById("slots");
          var items= slots.getElementsByTagName("li");

          var cookiestring = "";


          for (var i=1; i<items.length; i++)
          {

           var string = getItemInfo(items[i].className);
           cookiestring += string;
           


          }

          return cookiestring;


        }


        function getNoItems()
        {
		var slots=document.getElementById("slots");
		var items= slots.getElementsByTagName("li");
                
                var numberitems = items.length;

		//for (i=0; i<items.length; i++)
                return numberitems;

        }

        function getNoSlots()
        {
		var tr=document.getElementById("slots");
		var slots= tr.getElementsByTagName("ul");

                return slots.length;


        }

        function getFullSlots()
        {
		var tr=document.getElementById("slots");
		var slots= tr.getElementsByTagName("ul");
                var fullslots = slots.getElementsByTagName("li");

                var productId = new Array();

                for (i=0; i<fullslots.length; i++){
                   productId[i] = fullslots[i].id;
                }

               return productId;
                

        }
        function doesExist(id)
        {
          var cid = "c_" + id;

          if (document.getElementById(cid))
            {
             return true;
            }
            else
            {
            return false;
            }

//       for (key in Basket.basket)
//     	{
//  
// 							if (Basket.basket[key][0] == id)
// 							{
// 			
// 									if($('attr_'+id).value == ITEM_innerhtm)
// 									{
// 									}
// 									else
// 									{
// 									}
// 						}
//      }


        }

function changepanelname(agptitle)
{
document.getElementById("navigationx").innerHTML=agptitle;
}

	//THIS FUNCTION WRITE THE ITEM TO THE CART
	function writeToCart(owner_id, item_id, qty, details, custom, price, li_id, task, is_custom){
     if(task == "update"){
     var url = "misc_js.php?task=update_cart&owner_id="+owner_id+"&item_id="+item_id+"&qty="+qty+"&details="+details+"&custom="+custom+"&price="+price+"&li_id="+li_id;
     makeFrame(url);
     return;
     }
     if(task == "add"){
     var url = "misc_js.php?task=add_to_cart&owner_id="+owner_id+"&item_id="+item_id+"&qty="+qty+"&details="+details+"&custom="+custom+"&price="+price+"&li_id="+li_id+"&is_custom="+is_custom;
	 makeFrame(url);
	 return
	 }
	 
	 if(task == "remove"){
     var url = "misc_js.php?task=remove_from_cart&owner_id="+owner_id+"&item_id="+item_id+"&qty="+qty+"&details="+details+"&custom="+custom+"&price="+price+"&li_id="+li_id;
	 makeFrame(url);
	 return
	 }
	}
	




        function insertItem(id, price, agptitle, custom_bool, owner_id, comments)
        {
            var price = parseFloat(document.getElementById("item_total_price").value);
            price = price.toFixed(2);


              var product = document.getElementById(id);
              var item = product.cloneNode(true);

			  //see if the quantity in the get item popup has been adjusted
              var count = 1;
              if(document.getElementById('quantity_s'+id)){ count = parseInt(document.getElementById('quantity_s'+id).value);}
               if(count=="" || count ==0){alert("Please enter a valid quantity"); return;}
                
 			  var sattr_value = document.getElementById("attr_"+id).value;

            //check to see if the product is already in the basket or if it is not a customized object
              if(doesExist(id) && custom_bool=="false"){

			   //Increase the quantity on the product displayed in the shopping panel
               if(document.getElementById('quantity_c'+id) && document.getElementById('items_left_'+id).value > 0){
                var quantity_c_id = document.getElementById('quantity_c'+id);
                quantity_c_id.value = parseInt(document.getElementById('quantity_c'+id).value) + parseInt(count);
                item.id = "c_" + id;
                writeToCart(owner_id, id, quantity_c_id.value, '','', price, item.id, 'update');
                }
               
              }
              else
              {
					//if this is a customized product, create its own li
                    if(custom_bool == "true"){
                    
                     item.id = assignCustomId(id);
                     item.innerHTML = '<div style="width: 120px; background: url(images/transpix.png); border: 0px;color: #FFFFFF; font-size: 10pt; font-family: arial; font-weight:bold;" id="item_price_'+ id +'"><nobr>&nbsp;$'+price+'</nobr></div>';
                     
                     var storageprice = price;

             		 item.innerHTML += "<div style='position: relative; z-index: 1001; left: 100px; top: -42px;border: 0px;'><a href='javascript:removeItem("+ id + "," + storageprice + ", "+count+", \""+item.id+"\")'><img src='images/removeimage.png' width='37' height='37' border='0'></a></div>";
             		 item.innerHTML += "<div style='position: absolute; left: 5px; top: 73px; border: 0px;'><input type='hidden' name='id[]' value="+id+"><input class='cart_text' style='background: #eee; color:#888;' type='text' name='quantity[]' id='quantity_"+item.id+"_"+id+"' size='5' value='"+count+"' readonly><input type='hidden' name='sattr[]' id='sattr_"+id+"' value='"+sattr_value+"'></div>";
             		 item.innerHTML += "<div style='position: absolute; left: 70px; top: 70px; border: 0px;'><a href='javascript: getItemContent(" +id+  ", \""+ agptitle +"\",  \""+ item.id +"\");'><button class='pickup_button' style='width: 50px;'>EDIT</button></a></div>";

              
              		 item.className = id;

					 item.setAttribute('onmouseover', 'changepanelname(\''+ agptitle +'\')');
					 item.setAttribute('onmouseout', 'changepanelname(\'Shopping Panel\')');
                     
                     
                     writeToCart(owner_id, id, count, sattr_value,comments, storageprice, item.id, 'add', '1');
                    
                    }
                    else
                    {
 			 		 var storageprice = price;

             		 item.innerHTML += "<div style='position: relative; z-index: 1001; left: 100px; top: -42px;border: 0px;'><a href='javascript:removeItem("+ id + "," + storageprice + ", "+count+", 0)'><img src='images/removeimage.png' width='37' height='37' border='0'></a></div>";
             		 item.innerHTML += "<div style='position: absolute; left: 5px; top: 73px; border: 0px;'><input type='hidden' name='id[]' value="+id+"><input class='cart_text' type='text' name='quantity[]' id='quantity_c"+id+"' size='5' value='"+count+"' onkeypress='return isNumberKey(event)' onkeyup='changeQuantity(this.value,"+id+","+ storageprice +");' readonly><input type='hidden' name='sattr[]' id='sattr_"+id+"' value='"+sattr_value+"'></div>";

             		 item.id = "c_" + id;
              		 item.className = id;
              		 
              		 item.innerHTML += "<div style='position: absolute; left: 70px; top: 70px; border: 0px;'><a href='javascript: getItemContent(" +id+  ", \""+ agptitle +"\",  \""+ item.id +"\");'><button class='pickup_button' style='width: 50px;'>EDIT</button></a></div>";


					 item.setAttribute('onmouseover', 'changepanelname(\''+ agptitle +'\')');
					 item.setAttribute('onmouseout', 'changepanelname(\'Shopping Panel\')');
		
					 
					 writeToCart(owner_id, id, count, sattr_value,comments, storageprice, item.id, 'add', '0');
					}
					
              		var tr=document.getElementById("slots");
	          		var slots= tr.getElementsByTagName("ul");

              		 for (i=0; i<slots.length; i++) 
              		 {
             		   if (slots[i].className=='empty')
                		{
                   		slots[i].className='full';
                   		slots[i].appendChild(item);
                   		openPanel();
                   		addSlot();

                   		i = 1000;

                		}
               		  }
               		  
              }
              
                //decrease the number of items still available
			   if(document.getElementById('items_left_'+id).value > 0){ document.getElementById('items_left_'+id).value -= count;}
              
               //increase the global qty used
               if(document.getElementById('count_qty_total_'+id)){document.getElementById('count_qty_total_'+id).value = parseInt(document.getElementById('count_qty_total_'+id).value) + count;}

   

        }
        
        //this function will check the panel for custom objects and assign a custom id to the new custom object
        function assignCustomId(id, i){
         if(!(i>0)){i = 0;} 
         var custom_id = "custom_"+ i + "_" + id;
         if(document.getElementById(custom_id)){
          i++;
          return assignCustomId(id, i);
         }
         else
         {
          return custom_id;
         }
        }

        function removeItem(id, price, qty, custom_id)
        {
               var c_id = "c_" + id;
         	   //if custom item, get the custom object, else get the original object
               if(custom_id !=0){
                var custom = document.getElementById(custom_id);
                var item = custom;

                } else { var item=document.getElementById(c_id); }
			   if(custom_id !=0){
			    qty = document.getElementById('quantity_'+item.id+"_"+id).value; 
			    Basket.delFromBasket(id,price, qty, custom.id);
			    writeToCart('', id, qty, '','', price, custom.id, 'remove');
			   } else {
			    qty = document.getElementById('quantity_c'+id).value; 
			    Basket.delFromBasket(id,price, qty, 0);
			    li_id = "c_"+id;
			    writeToCart('', id, qty, '','', price, li_id, 'remove');
			   }
			   var parent = item.parentNode;
               parent.innerHTML = "";
               parent.className = "empty";
				/*
			   //check if the item is in cookie array, if so delete that entry
			   for (i=0; i<cookiearray.length; i++){
		  		 if(cookiearray[i][2] == id && cookiearray[i][4] == custom_id){
		  		  cookiearray.splice(i,1);
		   		  i = 1000;
		   		  cookiecounter--;
		   		 }
		  		}			
			   buildCookieString();
			   setCookie('shoppingpanel',cookietext,365);
			   */
        }
        
        
        
        
        
        
       //populate cookie array from cookie if set
        //cookiearray = checkCookie();
        //cookiecounter += parseInt(cookiearray.length);

        //check if the item is already in the cookie array
        function checkCookieArray(id, custom){
         if(custom !=""){ return false;} else{ return doesExist(id); }
        }
        
        //this function gets the info that will be used to populate the cookie
        /*function getItemCookieInfo(id, price, agptitle, custom, count, sattr_value, commentval){
		
		//if the item already exists, traverse the cookie array and update the quantity
		 var exists = checkCookieArray(id, custom);
		 if(exists){
		  for (i=0; i<cookiearray.length; i++){
		   if(cookiearray[i][2] == id && cookiearray[i][4] == ""){
		    cookiearray[i][6] = parseInt(cookiearray[i][6]) + parseInt(count);
		    i = 1000;
		   }
		  }
			
		 } else {

			//if the item has a custom id, or it does not exist in the panel, get the item info and add it to the cookie array
			cookiearray[cookiecounter] = new Array();
			cookiearray[cookiecounter][0] = itemstorage[id]['user_id'];
			cookiearray[cookiecounter][1] = itemstorage[id]['user_pic'];
			cookiearray[cookiecounter][2] = id;
			cookiearray[cookiecounter][3] = price;
			cookiearray[cookiecounter][4] = custom;
			cookiearray[cookiecounter][5] = agptitle;
			cookiearray[cookiecounter][6] = count;
			cookiearray[cookiecounter][7] = sattr_value;
			cookiearray[cookiecounter][8] = commentval;
			cookiecounter++;
          }
          buildCookieString();
          setCookie('shoppingpanel',cookietext,365);
		}
		
		function buildCookieString(){
		 cookietext ="";
		  for (i=0; i<cookiearray.length; i++){
		    if(i>0){cookietext+="<;>";}
		   	cookietext += cookiearray[i][0]  + "<,>" + cookiearray[i][1] + "<,>" + cookiearray[i][2] + "<,>" + cookiearray[i][3] + "<,>";
			cookietext += cookiearray[i][4] + "<,>" + cookiearray[i][5] + "<,>" + cookiearray[i][6] + "<,>" + cookiearray[i][7] + "<,>" + cookiearray[i][8];
	     }
		}*/
        
        
        function emptyPanel(owner_id){
       	 var answer = confirm("Are you sure you would like to clear the contents of your shopping panel?")
			if (answer){
		    document.getElementById('ajaxframe').src = "misc_js.php?task=empty_cart&owner_id="+owner_id;
			setCookie('shoppingpanel','',-10);
			setCookie('basketcontents','',-10);
		 	}
        }
    
        
        
        
        
        
        
        
        
        
        
        

        function sendToBasket(id)
        {
           
           var item_title = itemstorage[id]['title_full'];
           var item_price = itemstorage[id]['price'];
           var item_shipping = itemstorage[id]['shipping'];

           Basket.addToBasket(id,item_title,item_price,1,item_shipping,0);




        }
        function getItemInfo(id)
        {
           var item_title = itemstorage[id]['title_full'];
           var item_price = itemstorage[id]['price'];
           var item_shipping = itemstorage[id]['shipping'];

           var item_image = itemstorage[id]['image'];
           var item_owner_id = itemstorage[id]['user_id'];
           var item_owner_pic = itemstorage[id]['user_pic'];
    
           var inputid = "quantity_" + id;
           
           var quantity = document.getElementById(inputid).value;

           var cookiestring = id + "," + item_title + "," + item_price + "," + quantity + "," + item_shipping + "," + item_image + "," + item_owner_id + "," + item_owner_pic + " <>" ;

           return cookiestring;


        }


