
var xcatalog= new Connector('catalog');   
var xishop= new Connector('ishop');     
var SIZES=new Array('XS','S','M','L','XL', 'XXL', 'XXXL');

Array.prototype.find = function(searchStr) {
  var returnArray = false;
  for (i=0; i<this.length; i++) {
    if (typeof(searchStr) == 'function') {
      if (searchStr.test(this[i])) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    } else {
      if (this[i]===searchStr) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    }
  }
  return returnArray;
}




ping=function()
{
   xishop.execute({get_basket_data:true});     
}


function parseUrl(data) {
    var e=/^((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?$/;

    if (data.match(e)) {
        return  {url: RegExp['$&'],
                protocol: RegExp.$2,
                host:RegExp.$3,
                path:RegExp.$4,
                file:RegExp.$6,
                hash:RegExp.$7};
    }
    else {
        return  {url:"", protocol:"",host:"",path:"",file:"",hash:""};
    }
}

//работаем с интервалами
function add_sizes(interval)
{
    
    

    if(interval.indexOf('-')!=-1)
    {
        
        se=interval.split('-');                   
        start=SIZES.find(se[0]);     
        end=SIZES.find(se[1]);     
        
        s=document.createElement("select");
        s.id="size";    
          
        for(i=start[0];i<end[0]+1;i++)
        {            
             var option = document.createElement("option");
             option.value = SIZES[i];              
             var text = document.createTextNode(SIZES[i]);              
             option.appendChild(text);
             s.appendChild(option);
            
            
        }
        s.onchange=ishop.get_ostatok;
        $('#gabarits').html('');
        $('#gabarits')[0].appendChild(s);
        
    }
    
}

function add_select_options(selector,values)
{

    s=$('#'+selector)[0];
    options=values.split(',');
   
    for (i=0;i<options.length;i++)
    {
             var option = document.createElement("option");
             option.value = options[i];              
             var text = document.createTextNode(options[i]);              
             option.appendChild(text);
             s.appendChild(option);

   }

}


ishop={
        product:{color_name:null},        
        add:function()
        {
        if(this.product.color_name!=null)
        {
            data={};
            p=xoad.html.exportForm('product');
            if(size=$('#size')[0])
            {
                size=$('#size')[0][$('#size')[0].selectedIndex].value;
            }
            
            cimage=$('ul.select-color>li.selected a img')[0];
            image_path=parseUrl($('#oimage')[0].src);
                    jQuery.extend(data,{id:this.product.id,count:p.count},
                                {ext:{ 
                                    thisid:this.product.id,
                                    color_name:this.product.color_name,
                                    size:size,
                                    color_image: ishop.product.color_name,                                    
                                    color_title :ishop.product.title,                                    
                                    image_path:image_path.path+image_path.file,
                                    discount:ishop.product.discount,
                                    discounted_price:ishop.product.priceDiscounted,                                    
                                    generate_name_from:'color_name,size,name',                                                                    
                                    outer_price:ishop.product.price, 
                                    name :this.product.name+' ',
                                    generate_id_from:'thisid,name,color_name,size'}});            
            
                                $('#addtobasket').addClass('invisible');                                      
                                xishop.execute({add_product:data,get_basket_data:true});
                                
                                if(xishop.result.cart)
                                {
                                        this.refresh_cart(xishop.result.cart);
                                        $('#addtobasket').removeClass('invisible');                                      
                                        this.result('Товар добавлен в корзину');
                                }else{
                                        this.result('Ошибка!');
                                    
                                }
        
        }
        
        },
        
        
        grade_data:function()
            {    
                
                var prodarr=new Array(); 
               jQuery.each($("#baskettable> tbody >tr"),function()
                {
                                id=$(this).find("input[tag='id']")[0].value;                                     
                                prodarr[id]={};                                                                
                                prodarr[id].count=parseFloat($(this).find("input[tag='count']")[0].value); 
                                
               
               if(!ishop.nauth)
               {
                                prodarr[id].discount=parseFloat($(this).find("input[tag='discount']")[0].value);                       
                                prodarr[id].logotypename=$(this).find("input[tag='logotypename']")[0].value;
                                prodarr[id].printsize=$(this).find("input[tag='printsize']")[0].value;                     
                                prodarr[id].adjustment=$(this).find("input[tag='adjustment']")[0].value;                     
                                prodarr[id].printcount=$(this).find("input[tag='printcount']")[0].value;                     
                                prodarr[id].printcolor=$(this).find("input[tag='printcolor']")[0].value;                     
                                ptype=$(this).find("select[tag='printtype']");
                                prodarr[id].printtype=ptype[0].options[ptype[0].selectedIndex].value;
                                prodarr[id].discounted=parseFloat($(this).find("span.discounted")[0].innerHTML);                                  
                                prodarr[id].image=$(this).find("img")[0].src;  
               }
      
                    
                }
                );
                  
                return prodarr;
            },    

        create_price_save:function()
        {
                   

                             prodarr=this.grade_data();  
                             
                             xishop.execute({create_price_save:{prods:prodarr}});
                             
                             if(xishop.result.generated)
                             {
                                window.location.href='download.php';
                             }
               
        },  
        
      make_order:function()
      {
          prodarr=this.grade_data();            
          xishop.execute({saveorderdata:{prods:prodarr}}); 
      }
      , 
      
      create_price_client:function()
        {                   

                             prodarr=this.grade_data();  
                             xishop.execute({create_price_client_save:{prods:prodarr}});
                             if(xishop.result.generated)  
                             {
                                window.location.href='download.php';
                             
                             }
               
        },    
         
       
       
        result:function(m)
        {
            $('#result').html(m).fadeIn({duration:1000}).fadeOut();   
            
        }
       ,
         initoncart:function()
         {
                $("a.button[tag='symbolic']").click( function()                
                {                            
                    if($(this).attr("title")=='')
                    {   
                        $(this).find('.add-simb').html('Не наносить символику').removeClass('add-simb').addClass('del-simb');
                        $(this).next().next().slideDown();
                        $(this).attr('title','s');
                            }else{                        
                        $(this).find('.del-simb').html('Нанести символику').removeClass('del-simb').addClass('add-simb');
                        $(this).next().next().slideUp();
                        $(this).attr('title','');
                    }                    
                }
                
                )
                $("input[tag='discount']").change(ishop.recalculate).keypress(ishop.recalculate).keyup(ishop.recalculate);
                $("input[tag='count']").change(ishop.recalculate).keypress(ishop.recalculate).keyup(ishop.recalculate);
                //$("input[tag='printprice']").change(ishop.recalculate).keypress(ishop.recalculate).keyup(ishop.recalculate);        
         },
         
         recalculate:function()
         {
             sum=0;
             dsum=0;
             tr=$(this).parents("tr");
             
             if(ishop.nauth)
             {               
               discount=0;               
             }else{
                //скидка клиенту
               discount=parseFloat(tr.find("input[tag='discount']")[0].value);           
             
               //собственная скидка
               discounted=parseFloat(tr.find("span.discounted")[0].innerHTML);           
             }
             
             count=parseFloat(tr.find("input[tag='count']")[0].value);  
             
           /*  printprice=parseFloat(tr.find("input[tag='printprice']")[0].value);                                  
             if(isNaN(printprice)){printprice=0;}
            */ 
             
             
                price=parseFloat(tr.find("span.realprice")[0].innerHTML); 
                if(count>0)
                { 
                    sum=count*price;                    
                    if(discount!=0){
                        dsum=sum-(count*price)*discount/100;                                                                
                    }else
                    {dsum=sum;}
                   
                    sum=sum.toFixed(2);
                    dsum=dsum.toFixed(2);
                    
                    tr.find('span.productprice').html(sum);                    
                    
                    if(!ishop.nauth){                    
                        dtsum=(discounted*count).toFixed(2);
                        tr.find('span.productpriceydiscount').html(dtsum);   
                    }
                    
                    if(!ishop.nauth)
                    {
                        tr.find('span.productpricediscount').html(dsum);
                                 
                    }
                }
             
                
                _overall=0;
                
                
                jQuery.each($('span.productprice'),function()
                {
                     
                    if(!isNaN(z=parseFloat(this.innerHTML)))_overall+=z;
                    
                });
                
                _overall_discounted=0;
                jQuery.each($('span.productpriceydiscount'),function()
                {
                     
                    if(!isNaN(z=parseFloat(this.innerHTML)))_overall_discounted+=z;
                    
                });
                                _overall_discounted=_overall_discounted.toFixed(2);
                                _overall=_overall.toFixed(2);
                                $('#overall_discounted').html(_overall_discounted);
                                $('#overall').html(_overall);                            
                                $('#basketOrderSum').html(_overall);
                
             
         }
         ,
        refresh_cart:function(data)
        {
            $('#basketGoodsCount').html(data.goodsCount);
            $('#basketOrderSum').html(data.orderSum);
        }
        ,
        
        get_ostatok:function()
        {
            if(ishop.product.color_name)
            {
                s_ost=new Array();
                s_ost['articul']=ishop.product.articul;                        
                s_ost['color']=ishop.product.color_name;
                s_ost['id']=ishop.product.id;
                
                 if(size=$('#size')[0])
                {
                     s_ost['size']=$('#size')[0][$('#size')[0].selectedIndex].value;
                }
                           
                xcatalog.execute({get_ostatok:s_ost});
                    if(xcatalog.result.ostPoland)
                    {
                        $('#ostcontainerPoland').show();
                        $('#ostatokPoland').html(xcatalog.result.ostPoland);   
                    }else{
                        $('#ostcontainerPoland').hide();
                    }
                    
                if(xcatalog.result.ost)
                {
                    $('#ostcontainer').show();
                    $('#ostatok').html(xcatalog.result.ost);   
                    

                    
                    
                } else{                
                   $('#ostcontainer').hide();
                }
            }
                        
            
        } ,
        
        map_colors:function()
        {
         $('ul.select-color>li').click(
                
                function()
                {                              
                    $('#addtobasket').removeClass('invisible');
                    $('ul.select-color>li').removeClass('selected');
                    $(this).addClass("selected");
                    ishop.product=xoad.html.exportForm('product');             
                     var m =$('#oimage')[0].src.match(/(.*)[\/\\]([^\/\\]+)$/);
                     
                     if(m){$('#oimage')[0].src=m[1]+'/'+ishop.product.articul+'_'+$(this).attr("name")+'.jpg';}
                    
                    if(p=$(this).attr('price')){color_price=parseFloat(p).toFixed(2);}
                    if(n=$(this).attr('name')){ishop.product.color_name=n;}else{ishop.product.color_name='';}                                  
                    if(t=$(this).attr('title')){ishop.product.title=t}
                    
                    
                    ishop.product.price=color_price;
                    ishop.product.discount=parseFloat(ishop.product.discount).toFixed(2);                
                    
                    ishop.product.name=$('#productname')[0].innerHTML;
                    $('#price').html(ishop.product.price);
                    
                    
                    
                    if(!ishop.nauth)
                    {
                    ishop.get_ostatok();    

                      ishop.product.priceDiscounted=(ishop.product.price-ishop.product.discount*ishop.product.price/100).toFixed(2);                                            
                       $('#withDiscount').html(ishop.product.priceDiscounted);    
                    }
                  }
                
            );
               
        }

}





