// JavaScript Document
$(document).ready(function(){
  $("#backs").click(function(){
    history.back(-1);
  });
    
  $(".pspec, .pdesc").each(function(){
    $(this).html( $(this).text() );
  });
  
  $("#plist #qty").numeric();
  $('.div_body').fadeIn(1000);

//Set row background color
  $(".item_row:even").css("background-color", "#FFFFCC");
  $(".item_desc:even").css("background-color", "#FFFFCC");
  $(".item_row:odd").css("background-color", "#EEEEEE");
  $(".item_desc:odd").css("background-color", "#EEEEEE");
  
  $(".img_prom").each(function(){
    $(this).mouseenter(function(){
      $(this).parent().parent().find("#promDetail").show();
    }).mouseleave(function(){
      $(this).parent().parent().find("#promDetail").hide();
    });
    $(this).parent().parent().find("#promDetail").mouseenter(function(){
      $(this).show();
    }).mouseleave(function(){
      $(this).hide();
    });
  });
  
//Add all to cart  
  $("#add_all_cart").click(function(){
    var pcodelist = "";
    var ptype = 0; 
    var ctype = 0;
    var atleastqty = 0;
    var bln_change = true;
    var bln_bulk = true;
    $(".item_row").each(function(){
      var qty = $(this).find("#qty").val();
      if( qty > 0 ){
        pcode = $(this).find(".pcode").text();
        ptype = parseInt($(this).next().find("#pType:checked").val());
        ctype = parseInt($(this).next().find("#cType").val());
        atleastqty = parseInt($(this).next().find("#atleastqty:first").text());      
        bln_change = true;
        bln_bulk = true;
        
        location.href = '#'+pcode
        if( ctype != ptype && ctype > 0 ){
          if( !confirm( 'item: '+pcode + '\nDo you want change the price type?') ){
            bln_change = false;
          }
        }
        if( ptype == 3 && qty < atleastqty ){
          bln_bulk = false;
          $(this).parent().parent().next().find("#err_msg").stop(true, true).show().html("Order QTY at at least "+ atleastqty +"<br/>").fadeOut(6000);
          $(this).parent().parent().find("#qty").css("border","2px solid red");
        }
        
        if( bln_change && bln_bulk ){
          pcodelist += pcode + ",<br/>";
          var result = $.ajax({
            url: "add_shopping_cart.action",
            data: "product.prodId="+pcode+"&orderQty="+qty+"&priceType="+ptype,
            async: false
          }).responseText;
          $(this).find("#qty").val(0);
          $(this).find("#addcart").attr("src","images/prod_info/addtoCarted.gif");
          //$(this).next().find("#err_msg").show().html("uploading...").fadeOut(5000);
          $(this).find("#qty").css("border","1px solid #AAAAAA"); 
        }
      }
    });
    $.blockUI({  
            message:  '<span class="msg_content">'+pcodelist+' added to shopping cart.</span>', 
            timeout:   2000,
            css: { 
              width: '300px',
              border: 'none', 
              padding: '5px', 
              backgroundColor: '#FFF', 
              color: '#000' 
            }  
          });
    reload_cart();
  });
  
//---------  Product List------------------------------------------------------------
  $(".item_row").each(function(){

//Check different pricing
//btpye: 7 = Prom + Bulk + Normal; 5 = Prom + Normal; 3 = Bulk + Normal; 1 = Normal
//cType: choice type
  var bType = parseInt($(this).next().find("#bType").val());
  var cType = parseInt($(this).next().find("#cType").val());

  if( cType > 0 ){
    $(this).next().find('#pType').each(function(){
      if( $(this).val() == cType ){
        $(this).attr('checked', true);
      };
    });
  }else{
/*
    if( bType >= 5 || bType == 1){
      $(this).next().find('#pType:radio:eq(0)').attr('checked', true);
    }else{
      $(this).next().find('#pType:radio:eq(1)').attr('checked', true);
    }
*/
 $(this).next().find('#pType:radio:eq(0)').attr('checked', true);

  }
    
  if( bType <= 1 ){
    $(this).next().find('#selprice').hide();
  }  

//Choice the pricing
  $(this).find('#pType:radio').change(function(){
  });
	  
//Click increse button
    $(this).find("#add_qty").click(function(){
      if( $(this).parent().parent().find("#qty").val() < 99999 ){
        $(this).parent().parent().find("#qty").val( parseInt($(this).parent().parent().find("#qty").val())+1 );
      }
    })
//Click decrese button  
    $(this).find("#min_qty").click(function(){
      if( $(this).parent().parent().find("#qty").val() > 0 ){
        $(this).parent().parent().find("#qty").val( parseInt($(this).parent().parent().find("#qty").val())-1 );
      } 
    })
//Click product code  
    $(this).find("#cart_prod").click(function(){
      var pcode = $(this).text();
      $(this).text(load+"...");
      var pname = $(this).parent().parent().find(".pname").text();
      window.location.href = 'prod_detail.action?product.prodId='+pcode+'&keyword='+pname;
    }) 
//Set 2 d.p.  
    $(this).find(".prod_price").each(function(){
      $(this).text( "$"+format_number($(this).text(),2) );
    });
    $(this).find("#prom_item").text( "$"+format_number($(this).find("#prom_item").text(),2) );
    
//Add to cart    
    $(this).find("#addcart").click(function(){
      item_row = $(this).parent().parent();
      oimg = $(this).attr("src"); 
      var qty = parseInt(item_row.find("#qty").val());
      var pcode = item_row.find("#cart_prod").text();      
      var ptype = parseInt(item_row.next().find("#pType:checked").val());
      var ctype = parseInt(item_row.next().find("#cType").val());
      var atleastqty = parseInt(item_row.next().find("#atleastqty:first").text());      
      var bln_change = true;
      var bln_bulk = true;
      
      if( ctype != ptype && ctype > 0 ){
        if( !confirm('Do you want change the price type?') ){
          bln_change = false;
        }
      }
      if( ptype == 3 && qty < atleastqty ){
        bln_bulk = false;
        $(this).parent().parent().next().find("#err_msg").stop(true, true).show().html("Order QTY at at least "+ atleastqty +"<br/>").fadeOut(6000);
        $(this).parent().parent().find("#qty").css("border","2px solid red");
      }
      if( bln_change && bln_bulk ){  
        if( qty > 0 ){
          var result = $.ajax({
            url: "add_shopping_cart.action",
            data: "product.prodId="+pcode+"&orderQty="+qty+"&priceType="+ptype,
            async: false
          }).responseText;        
          item_row.find("#qty").val(0);
          $(this).attr("src","images/prod_info/addtoCarted.gif");
          item_row.next().find("#err_msg").stop(true, true).show().html( uploading + "...<br/>").fadeOut(5000);
          item_row.find("#qty").css("border","1px solid #AAAAAA");
          item_row.find("#cType").val( ptype );
          //show_update_msg();
          reload_cart();        
        }else{
          item_row.next().find("#err_msg").stop(true, true).show().html("QTY must greater then 0 or numeric.<br/>").fadeOut(6000);
          item_row.find("#qty").css("border","2px solid red");
        }
      }
    });
//Add to Buying list
    $(this).find("#addbuy").click(function(){
      if( $(this).attr("src").indexOf("png") >= 0 ){ 
        var pcode = $(this).parent().parent().find("#cart_prod").text();  
      	var result = $.ajax({
      	  url: "add_freq_buy_list",
        	data: "product.prodId="+pcode,
        	async: false
      	}).responseText;
      	$(this).parent().parent().next().find("#err_msg").show().html("Adding to frequent buying list...<br/>").fadeOut(5000);
      	$(this).attr( "alt","Added frequeny buying list" );
      	$(this).attr( "src","images/prod_info/addedbuying.gif" );
    	}
    });
//Add to Buying list by multi list
    $(this).find("#but_add_buying").click(function(){
      var pcode = $(this).parent().parent().parent().find("#cart_prod").text();  
      var buying_id = $(this).parent().find('#mc_id').val();
      
      var result = $.ajax({
      	  url: 'add_freq_buy_list',
        	data: 'product.prodId='+pcode+'&fblh.id='+$('#mc_id').val(),
        	async: false
      	}).responseText;
      	$(this).parent().parent().parent().next().find("#err_msg").show().html("Adding to frequent buying list...<br/>").fadeOut(5000);
      	$(this).parent().parent().find("#buying_frame").hide();
    });
//Show add Buying List    
    $(this).find('#showbuy').click(function(){
      $(this).parent().find('#buying_frame').show();
    });                              
//Delete Buying list item
    $(this).find("#removelist").click(function(){
      if( $(this).attr("src").indexOf("png") >= 0 ){ 
        var pcode = $(this).parent().parent().find("#cart_prod").text();
        var pnos = $(this).parent().parent().find("#pnos").text();
        var result = $.ajax({
    	  	url: "del_freq_buy_list",
      		data: "product.prodId="+pcode+'&fblh.id='+$('#buying_id').val(),
      		async: false
    	  }).responseText;
    	  $(this).parent().parent().hide();
    	  $(this).parent().parent().next().hide();
    	  //members[pnos] = "";
    	}
    });
   
  });
  
  $('.item_desc').each(function(){
    var pspec = $(this).find('.pdesc').text();
    pspec = pspec.substr(0,60);
    $(this).find('.pdesc').text( pspec );
    
    $(this).find(".prod_price").each(function(){
      $(this).text( "$"+format_number($(this).text(),2) );
    });
  });
  
//Javascript Pagination Calculate:Start--------------------------------------------------------------------
  $("#maxpage").val( $("#wmaxPage").text() );
  $("#pageno").val( $("#wpageNo").text() );
  $("#tpage").val( $("#wtotPage").text() );
  $("#scparent").val( $("#wscParent").text() );
  $("#scid").val( $("#wscId").text() );
  $("#vtype").val( $("#wvtype").text() );
    
  pagenum = parseInt($("#pageno").val())+1;
  lastnum = $("#tpage").val();
  
  $('.pagers').each(function(){
    if( lastnum < 11 ){
      firstpage = 1;
      lastpage = lastnum;
    }else if( pagenum <= 5 ){
      firstpage = 1;
      lastpage = firstpage + 10;
      $(this).find("#p12").show();
    }else if( (lastnum - pagenum) <= 5 ){
      lastpage = lastnum;
      firstpage = lastnum - 10;
      $(this).find("#p0").show();
    }else{
      firstpage = pagenum - 5;
      lastpage = pagenum + 5;
      $(this).find("#p0").show(); 
      $(this).find("#p12").show();
    }
    j = 1;
    for( i = firstpage; i <= lastpage; i++ ){
      $(this).find("#p"+j).text(i);
      if( i == pagenum ){
        $(this).find("#p"+j).css("color","red").css("text-align","center").attr("class","sel");
      }
      j++;    
    }

    $(this).find("#p0").click(function(){
      $("#pageno").val(  parseInt($("#pageno").val())-1 );
      dopagersumit();
    })
    $(this).find("#p12").click(function(){
      $("#pageno").val(  parseInt($("#pageno").val())+1 );
      dopagersumit();
    }) 
  });  
  
//Javascript Pagination Calculate:End

//Javascript Pagination Click Event
  $(".pagno, .spagno").each(function(){
    $(this).hover(function(){
      $(this).css("font-size","18px");
    }, function(){
      $(this).css("font-size","12px");
    })
  })
  
  $(".pagno").click(function(){
    $("#pageno").val( parseInt($(this).text())-1 );
    if( $("#pageno").val() >= 0 ){
      dopagersumit();
    }
  })  
//Javascript Pagination Click Event 

  $("#plist_image").click(function(){
    $("#vtype").val(1);
    dopagersumit();
  })
  $("#plist_detail").click(function(){
    $("#vtype").val(0);
    dopagersumit();
  })
  
  
});

function dopagersumit(){
  urls = location.href.split("/")[3].split("?");
  if( urls[1] == "searchProd.action" ){
    $("#frmPage").attr("action", urls[0]);
  }else{
    $("#frmPage").attr("action", urls[0]);
  }
  $("#frmPage").submit();
  $.blockUI({  
    message:  '<span class="msg_content"><img src="images/loader/loader.gif" />'+loading+'</span>', 
    css: { 
      width: '300px',
      border: 'none', 
      padding: '5px', 
      backgroundColor: '#FFF', 
      color: '#000' 
    }  
  }); 
}
//====================================================================================================================

function doc_ready(){
  $(".prom_items").each(function(){
//Mouse On   
    $(this).hover(
      function(){ $(this).parent().css("color","black");},
      function(){ $(this).parent().css("color","#888888");
      }
    );
//Mouse On Product Code    
    $(this).find(".pname").hover(
      function(){ $(this).css("color", "blue");},
      function(){ $(this).css("color", "#888888");
      }
    );
//Click to Product Detail    
    $(this).click(function(){
      var pcode = $(this).attr("pid");
      $(this).parent().find("#err_msg").text('Loading');
      window.location.href = 'prod_detail.action?product.prodId='+pcode;
    });
//Set Number Format
    $(this).find(".oldprice").html( "<del>$" + format_number($(this).find(".oldprice").text(),2) + "</del>");
    $(this).find(".promprice").html( "$" + format_number($(this).find(".promprice").text(),2) );
  });
     
  $(".add_item").each(function(){  
//Add to ShoppingCart
    $(this).click(function(){      
      oimg = $(this).attr("src"); 
      $(this).attr("src","images/create_order/update_qty.gif");
      var qty = parseInt($(this).parent().find("#qty").val());
      var pcode = $(this).parent().find("#addcart").attr("pid");
      if( qty > 0 ){
        var result = $.ajax({
          url: "add_shopping_cart",
          data: "product.prodId="+pcode+"&orderQty="+qty+"&priceType=2",
          async: false
        }).responseText;
        
        $(this).parent().find("#qty").val(0);
        $(this).attr("src","images/prod_info/addtoCarted.gif");
        //$(this).parent().find("#err_msg").show().html("uploading...<br/>").fadeOut(5000);
        $(this).parent().find("#qty").css("border","1px solid #AAAAAA");
        show_update_msg();
        if( $(this).attr("id") == "qadd" ){
          window.location.href = 'list_shopping_cart.action';
        }else{
          reload_cart();;
        }        
      }else{
        $(this).parent().find("#err_msg").show().html("QTY must greater then 0 or numeric.<br/>").fadeOut(6000);
        $(this).parent().find("#qty").css("border","2px solid red");
        $(this).attr("src",oimg);
        $("#dialog_box").show(); 
        $("#dialog_box #message").html( "Error<br/>");
      }
    });
  });
}

//Promotion
function pageselectCallback_prom(page_index, jq){
  var max_elem = Math.min((page_index+1) * items_per_page, members.length);
  //var newcontent = "<table border='0' > ";
  var newcontent = "";
                
  for( var i = page_index*items_per_page ; i < max_elem ; i++ ){
    newcontent += "<div id='main_prom'><table width='230' height='400' border='0' bgcolor='#FFFFFF'>";
    
    newcontent += "<tr class='prom_items' height='120' pid='"+members[i][0]+"'><td align='left' valign='bottom' colspan='3'><img src='images/product/"+ members[i][1] +"'  alt='"+ members[i][3] +"' id='prom_img' width='120' height='120'/><img src='images/product/"+ members[i][3] +"' alt='Gift' id='prom_icon' width='80' height='60'/></td></tr>";

    newcontent += "<tr height='100' class='gift_items' valign='top'>";    
    if( members[i][7].length > 1 ){ 
      newcontent += "<td align='right' width='210' >";
      if( members[i][7][0] > 1 ){  
        for( k = members[i][7][0]; k > 0; k-- ){        
          newcontent += "<img src='images/product/"+ members[i][7][k][1] +"' alt='"+ members[i][7][k][2] +"' width='30' height='30' id='prom_gift' class='prom_gift'/>";            
        }                                                                                                                                                               
      }
      newcontent += "</td><td><img src='images/product/"+ members[i][7][1][1] +"' alt='"+ members[i][7][1][2] +"' width='100' height='100' id='prom_gift_large'/></td></tr>";            
      newcontent += "<tr class='prom_items' pid='"+members[i][0]+"'><td colspan='2' align='left' valign='top'><span id='giftname'>"+ members[i][7][1][2] +"</span></br><br/>";
    }else{
      newcontent += "<td align='center' >";
      newcontent += "&nbsp;</td></tr>";      
      newcontent += "<tr class='prom_items' pid='"+members[i][0]+"'><td colspan='2' align='left' valign='top'>";
    }
  
    newcontent += "<span class='pname'>"+members[i][2] +"</span><br/>";
    newcontent += members[i][0] +"<br/>";
    if( parseFloat(members[i][4]) > parseFloat(members[i][5]) && parseFloat(members[i][5]) > 0 ){
      newcontent += "<span class='oldprice'>"+ members[i][4] +"</span>&nbsp;<span class='promprice'>"+ members[i][5] +"</span> / "+ members[i][6] ;
    }else{
      newcontent += "<span class='special'>Special Offer</span>";
    }  
    newcontent += "</td></tr><tr><td colspan='2'>";
    newcontent += "<div align='right' id='butt'>";
      newcontent += "<input type='text' value='1' size='1' maxlength='5' id='qty'/>";
      newcontent += "<img src='images/prod_info/addtoCart.png' alt='Add to Cart' id='addcart' class='add_item' pid='"+members[i][0]+"'/>";
      newcontent += "<img src='images/prod_info/quickorder.png' alt='Quick Order' id='qadd' class='add_item' />";
      newcontent += "<div id='err_msg'></div>";
    newcontent += "</div>";    
    newcontent += "</td></tr>";
    newcontent += "</table></div>";

  }
  $('#Searchresult').html(newcontent);
  
  $('.prom_gift').each(function(){
    $(this).hover(function(){
      $(this).parent().parent().parent().find('#prom_gift_large').attr('src', $(this).attr('src'));
      $(this).parent().parent().parent().find('#giftname').text( $(this).attr('alt') );
    });
  });
location.href  = '#top';
      
  doc_ready();
        
  return false;
}

function addtoCart(this_selector){
}
function show_update_msg(){
  $.blockUI({   
    message:  '<span class="msg_content">Uploading...</span>', 
    timeout:   500,
    css: { 
      width: '300px',
      border: 'none', 
      padding: '5px', 
      backgroundColor: '#FFF', 
      opacity: .9 , 
      color: '#000' 
    } 
  });
}

