var isZoomActive = 0;


//product selection
$j(".sizeBlock > a").live("click", function() {
    //changing bkg of clicked element
    $j(".selectedSize").addClass("notSelectedSize");
    $j(".selectedSize").removeClass("selectedSize");

    $j(this).parent(".sizeBlock").removeClass("notSelectedSize");
    $j(this).parent(".sizeBlock").addClass("selectedSize");
    //
    var size = $j(this).attr("rel");
    
    // Get product id.
    // Get the image path from the main view.
    var mainView = $j('.magMeLink').attr('href'); // /images/prodno/filename.
    var mpos1     = mainView.lastIndexOf('/');
    var mpos2     = mainView.lastIndexOf('/', mpos1-1);
    var mprodId   = mainView.substr(mpos2+1, mpos1-mpos2-1);
    
    // Get the type of mango description to be pulled from db.
    // The responce can be 1 or 2.
    // 1: mango_size_desc1, 2: mango_size_desc2.
     
    /*     
    var xhr = $j.ajax(
        {
            url      : webroot + 'product/get-product-type/prodId/'+mprodId,
            type     : 'get',
            dataType : 'text',
            async    : 'false',
            complete : function(oXHR){
                            mango_type = oXHR.responseText;                        
                        }
        }
     );
     */
 
 
     var xhr = $j.get(webroot + 'product/get-product-type/prodId/'+mprodId, 
        {},
        function(response)
        {
            var error = false;
            // If error then exit;
            if( xhr.status != 200 ) 
            {    
                error = true;
            }
            if( ( ! error ) && ( response != "" ) && ( response > 0 ) )
            {
               // Update getInfoDetails.
               $j("#getInfoDetails").load(webroot+'product/get-size-info/which_desc/'+ response +'/size/'+size,
                   function(){
                              if($j("#getInfoDetails").html() != "")
                                {$j(".getinfo").show();
                                 //  alert($(this).html());
                                 }
                              else
                              {
                                 $j(".getinfo").hide();
                                 $j("#getInfoDetails").html("");
                              }       
                           });
             }             
        });
    
    var category_id = $j("#category_id").val();
    new Ajax.Updater('colorSelect', webroot + 'product/get-color/category_id/' + category_id + '/size/' + size + '/ajax/true', {
        onCreate: function() { $j('#colorSelect').text('Loading...'); },
        onComplete: checkSingleColor
    });
    
    return false;
});



function checkSingleColor(transport) {
    if($j(".colorBlock > a").size() == 1) {
        $j(".colorBlock > a").trigger("click");
    }
}

$j(".colorBlock > a").live("click", function() {
   var products_id = $j(this).attr("rel");
   $j("#selectedProduct_id").val(products_id);
   
   //change image
   var image = $j(this).find("img").attr("src");
   var imageName = $j(this).find("img").attr("alt");
   imgTag = "CULOARE: &nbsp;&nbsp;&nbsp;<img style='position:relative; top:3px;' src='" + image + "' alt='' /> &nbsp;&nbsp;&nbsp;" + imageName;
   $j(".selectedColor").html(imgTag);
   //////////////
   
   return false;
});

$j(document).ready(function(){
   $j('#mapImageId').live("click",function(){alert('ok');});
});

//Magnify Picture.
$j(document).ready(function(){
    $j('.magMe').live( "mouseover", function(e){

      
   });
   
    $j('.magMe').live("mousemove", function(e){
    
      //MOUSEOVER (CREATE ELEMENT) =================================================
      if(! isZoomActive ) {
      isZoomActive = 1;
      var magPlaceWidth = this.offsetWidth-20;
      var magPlaceHeight = this.offsetHeight-40;
      /*var link = this.parentNode.href;
      var pos1 = link.lastIndexOf('/');
      var pos2 = link.lastIndexOf('/', pos1-1);
      var prodNo = link.substr(pos2+1, pos1-pos2-1);
      */
      var fullPath = this.parentNode.href;
      var pos1     = fullPath.lastIndexOf('/');
      var pos2     = fullPath.lastIndexOf('/', pos1-1);
      var prodNo   = fullPath.substr(pos2+1, pos1-pos2-1);
      var fileName = fullPath.substr(pos1+1);
      
      
      
      
      var magPlace = $j('div.magPlace');

      magPlace.width(magPlaceWidth+"px");
      magPlace.height(magPlaceHeight+"px");
      magPlace.css("display","block");

      var img = new Image();
      img.src = "/images/" + prodNo + "/" + fileName;
      img.id = "maggedPic";
      magPlace.append(img);
      
      
      //var imageLeft = this.offsetLeft;
      var imageLeft = $j(this).offset().left;
      var imageRight = this.offsetRight;
      //var imageTop =  this.offsetTop;
      var imageTop =  $j(this).offset().top;
      var imageWidth = this.offsetWidth;
      var imageHeight = this.offsetHeight;
      
      
      scalex = Math.round(img.offsetWidth / imageWidth);
      scaley = Math.round(img.offsetHeight / imageHeight);
      scrollx = e.pageX - imageLeft - (magPlaceWidth/scalex)/2;
      scrolly = e.pageY - imageTop - (magPlaceHeight/scaley)/2;


      magPlace.get(0).scrollTop  = scrolly * scaley;
      magPlace.get(0).scrollLeft = scrollx * scalex; 
      
      }
      // EOF MOUSEOVER (CREATE ELEMENT) =================================================
    
      var magPlaceWidth = this.offsetWidth-20;
      var magPlaceHeight = this.offsetHeight-40;   
       /*var link = this.parentNode.href;
      var pos1 = link.lastIndexOf('/');
      var pos2 = link.lastIndexOf('/', pos1-1);
      var prodNo = link.substr(pos2+1, pos1-pos2-1);
      */
      var fullPath = this.parentNode.href;
      var pos1     = fullPath.lastIndexOf('/');
      var pos2     = fullPath.lastIndexOf('/', pos1-1);
      var prodNo   = fullPath.substr(pos2+1, pos1-pos2-1);
      var fileName = fullPath.substr(pos1+1);
      var magPlace = $j('div.magPlace');

      //magPlace.width(magPlaceWidth+"px");
      //magPlace.height(magPlaceHeight+"px");
      magPlace.css("display","block");


      var img = document.getElementById("maggedPic");
       
      var imageLeft = this.offsetLeft;
      var imageRight = this.offsetRight;
      var imageTop =  this.offsetTop;
      var imageWidth = this.offsetWidth;
      var imageHeight = this.offsetHeight;
    
     //alert(img.offsetWidth);
     //alert(img.offsetHeight);
     //alert(imageHeight);
     //alert(document.getElementWidth(img));

     // var aaa = $j('maggedPic').css('width');
     // alert(aaa);
     // return;
     //alert(img.width);

     //alert(img.height);
      var scalex = img.offsetWidth / imageWidth;
      var scaley = img.offsetHeight / imageHeight;

      var resX = Math.round((e.pageX - $j(this).offset().left) * scalex);
      var resY = Math.round((e.pageY - $j(this).offset().top) * scaley);
      var ratio = img.offsetWidth / img.offsetHeight;
      
      magPlace.get(0).scrollLeft =  resX - ((resX/2) * (ratio*0.3));
      magPlace.get(0).scrollTop  = resY - ((resY/2) * (ratio*0.5));
    });    
    
     $j('.magMe').live( "mouseout", function(){
        isZoomActive = 0;
        var magPlace = $j('div.MagPlace img');
        var chNodes  = document.getElementById('magPlace').childNodes;
        var parent =  document.getElementById('magPlace');
        for(i=0; i < chNodes.length; i++)
            parent.removeChild(chNodes[i]);
            
        parent.style.display = "none";
        magPlace.css("display","none");
    });

});


$j('.putMeImage').live("click", function(){
    var fullPath = $j(this).attr('src');
    var pos1     = fullPath.lastIndexOf('/');
    var pos2     = fullPath.lastIndexOf('/', pos1-1);
    var pos3     = fullPath.lastIndexOf('/', pos2-1);
    var prodNo   = fullPath.substr(pos3+1, pos2-pos3-1);
    var fileName = fullPath.substr(pos1+1);
    $j('.productImage').css('background-image', 'url(/media/get-thumb/width/260/folder/' + prodNo + '/file/' + fileName +')');
    var bkFullPathName = $j('.productImage').css('background-image');
    var t1 = bkFullPathName.substr(4, bkFullPathName.length-5);
    var t2 = t1.substr(23);

    // Get the image path from the main view.
    var mainView = $j('.magMeLink').attr('href'); // /images/prodno/filename.
    var mpos1     = mainView.lastIndexOf('/');
    var mpos2     = mainView.lastIndexOf('/', mpos1-1);
    var mprodNo   = mainView.substr(mpos2+1, mpos1-mpos2-1);
    var mfileName = mainView.substr(mpos1+1);
    
    
    
    
    
    
    $j(this).attr('src', '/media/get-thumb/width/61/folder/' + mprodNo + '/file/' + mfileName );
    // Put the big image for the same product to be used in the magnification process.
    $j('.magMeLink').attr('href', '/images/' + prodNo + '/' + fileName);

      //  <img class="putMeImage" src="<?= $this->url(array("controller" => "media", "action" => "get-thumb", "width" => "61", "folder" => $this->product['categories_id'], "file" => $file)) ?>" alt="" />
    //$j('.productImage').css('background', 'width=url('+fullPath+')');
//    alert(fullPath);
    //$j('.magMe').attr('src', '/images/' + prodNo + '/' + fileName);
});
//adaugare cos
$j("#buyNow").live("click", function() {
    if(! $j("#selectedProduct_id").val()) {
        
        var alertURL = webroot + "messages/no-product-selected/";
        ALERT_show('', alertURL);
        
        return false
    }
    
    var product_id = $j("#selectedProduct_id").val();
    
    if($j("#impachetareCadou").attr("checked")) {
        product_id += ", " + $j("#impachetareCadouProductId").val() ;
    }
    
    new Ajax.Request
    (
        '/default/cart/add/shop/' + module + '/id/' + product_id,
        {
            method: 'get',
            onSuccess: function(transport) { 
            
                var successURL = webroot + "messages/product-add-success/";
                ALERT_show('', successURL);
                
                //update cart info 
                updateCartInfo();
                
            }
        }
    );
    
    return false;
});



$j(document).ready(function() {
    $j("#buyNow").find("img").hover(
        function() {
            this.src = this.src.replace("2", "1");
        },
        
        function() {
            this.src = this.src.replace("1", "2");
        }
    );
});

$j(document).ready(function () {
    $j("#impachetareCadou").siblings("a").toggle(
        function () {
            $j(this).prev(":checkbox").attr("checked", "checked");
            $j(this).find("img").attr("src", webroot + "img/product/bifa-2.gif");
        }, 
        function() {
            $j(this).prev(":checkbox").attr("checked", "");
            $j(this).find("img").attr("src", webroot + "img/product/bifa-1.gif");
        }
    );
});

$j(document).ready(function() {
    if($j(".sizeBlock > a").size() == 1) {
        $j(".sizeBlock").find("a").trigger("click");
    }  else if($j(".sizeBlock > a").size() == 0) {
        $j("#buyNow").parent("div").html("<div style='margin:40px auto; text-align:center; font-weight:bold;'>Stoc Epuizat / Produs Indisponibil</div>");
    }
});

function adaugaGiftCardCos(counter)
{
   productId = $('giftCardSelect_' + counter).value;
   location.href= '/cart/add/id/' + productId + '/quantity/1'; 
}

function displayAssociationLink(categories_id)
{
    $('association_' + categories_id).style.display = 'block';
    $('association1_' + categories_id).style.display = 'block';
}

function closeAssociationLink(categories_id)
{
    $('association_' + categories_id).style.display = 'none';
    $('association1_' + categories_id).style.display = 'none';
}

function openProductLink(categories_id)
{
    location.href= '/product/description/id/' + categories_id;
}


///category-product ajax
$j(".ProductThumb > a").live("click", function() {
    var url = $j(this).attr("href");
    
//    new Ajax.Updater("productDescriptionAjax", url + "/ajax/true", {
//        onCreate: function() { $('productDescriptionAjax').innerHTML = 'Loading...' },
//        onSuccess: initDescription
//    });
    
    $j("#productDescriptionAjax").html("<img class='loadingAnimation' src='" + webroot + "img/loadingAnimation.gif' alt='Loading...' />");
    $j("#productDescriptionAjax").load(url + "/ajax/true", initDescription);
    
    return false;
});


//ajax pagination
$j(".paginationControl").find("a").live("click", function() {
    var url = $j(this).attr("href");
    
    if(! url.match("list-products-ajax")) {
        url = url.replace("list-products", "list-products-ajax");
    }
    
    $j("#productListingAjax").html("<img class='loadingAnimation' src='" + webroot + "img/loadingAnimation.gif' alt='Loading...' />");
    $j("#productListingAjax").load(url);
    
    return false;
});


//ajax filters (tip model)
$j(".CategoryListingFilter").find("a").live("click", function() {
    var url = $j(this).attr("href");
    var currentPrice = $j("#currentPriceRange").val();
    var currentStyle = $j("#currentStyle").val();
    var category_id = $j(this).attr("rel");
    $j("#currentCategory").val(category_id);
    $j("#currentCategoryText").text($j(this).text());
    
    if(! url.match("list-products-ajax")) {
        url = url.replace("list-products", "list-products-ajax");
    }
    
    url = url + "/attribute_value_id/" + currentStyle + "/price/" + currentPrice;
    
    $j(".DropDown").hide();
    $j("#productListingAjax").html("<img class='loadingAnimation' src='" + webroot + "img/loadingAnimation.gif' alt='Loading...' />");
    $j("#productListingAjax").load(url, updateAssociation);
    
    return false;
});

//ajax filters (stil)
$j(".CategoryStyleFilter").find("a").live("click", function() {
    var currentCategory = $j("#currentCategory").val();
    var currentPrice = $j("#currentPriceRange").val();
    var style = $j(this).attr("rel");
    $j("#currentStyle").val(style);
    $j("#currentStyleText").text($j(this).text());
    var url = webroot + "category/list-products-ajax/id/" + currentCategory + "/price/" + currentPrice + "/attribute_value_id/" + style;
    
    
    
    if(! url.match("list-products-ajax")) {
        url = url.replace("list-products", "list-products-ajax");
    }
    
    $j(".DropDown").hide();
    $j("#productListingAjax").html("<img class='loadingAnimation' src='" + webroot + "img/loadingAnimation.gif' alt='Loading...' />");
    $j("#productListingAjax").load(url);
    
    return false;
});

//ajax filters (price)
$j(".CategoryPriceFilter").find("a").live("click", function() {
    var currentCategory = $j("#currentCategory").val();
    var currentStyle = $j("#currentStyle").val();
    var price = $j(this).attr("rel");
    $j("#currentPriceRange").val(price);
    $j("#currentPriceText").text($j(this).text());
    var url = webroot + "category/list-products-ajax/id/" + currentCategory + "/price/" + price + "/attribute_value_id/" + currentStyle;
    
    if(! url.match("list-products-ajax")) {
        url = url.replace("list-products", "list-products-ajax");
    }
    
    $j(".DropDown").hide();
    $j("#productListingAjax").html("<img class='loadingAnimation' src='" + webroot + "img/loadingAnimation.gif' alt='Loading...' />");
    $j("#productListingAjax").load(url);
    
    return false;
});

function updateAssociation()
{
    var currentCategory = $F("currentCategory");
    var url = webroot + "category/category-images/categoryId/" + currentCategory + "/ajax/true";
    
    $j("#categoryAssociation").html("<img class='loadingAnimation' src='" + webroot + "img/loadingAnimation.gif' alt='Loading...' />");
    $j("#categoryAssociation").load(url);
}

function initDescription(transport)
{        
    tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
    ALERT_init('a.alertbox, area.alertbox, input.alertbox');
    
    $j("#buyNow").find("img").hover(
        function() {
            this.src = this.src.replace("2", "1");
        },
        
        function() {
            this.src = this.src.replace("1", "2");
        }
    );
    
    $j("#impachetareCadou").siblings("a").toggle(
        function () {
            $j(this).prev(":checkbox").attr("checked", "checked");
            $j(this).find("img").attr("src", webroot + "img/product/bifa-2.gif");
        }, 
        function() {
            $j(this).prev(":checkbox").attr("checked", "");
            $j(this).find("img").attr("src", webroot + "img/product/bifa-1.gif");
        }
    );
    
    if($j(".sizeBlock > a").size() == 1) {
        $j(".sizeBlock").find("a").trigger("click");
    } else if($j(".sizeBlock > a").size() == 0) {
        $j("#buyNow").parent("div").html("<div style='margin:40px auto; text-align:center; font-weight:bold;'>Stoc Epuizat / Produs Indisponibil</div>");
    }
    
    
    $j(".rounded").corner();
    
}
