var $j = jQuery.noConflict();

$j(document).ready(function(){
 
 nohide = false;
 
 if (module_enabled()){
 if(!inComparePopUp()){
 update();
 }else{
 comparePopUpLinks();
 }
 }
 
 var eapUrl = gup('eapUrl');
 if (eapUrl != ""){
 new $j.ajax({
 url: "http://"+eapUrl+"eap/1/",
 type: "GET",
 dataType: "html",
 success: function(msg){
 callbacks(msg, 5);
 }
 });
 }
});

function comparePopUpLinks(){
 if (compare_add_to_cart_enabled()){
 $j('button[onClick*=cart/add]').each(function() {
 var $t = $j(this);
 var splitting = $t.attr('onClick').toString().split("'");
 
 $t.attr('link' , splitting[1] );
 $t.removeAttr('onclick');

 $t.click(function() {
 window.opener.addProduct($t);
 });
 });
 }
 
 if (wishlist_add_enabled()){
 $j('a[onClick*=wishlist/index/add]').each(function(){
 
 var $t = $j(this);
 
 var splitting = $t.attr('onClick').toString().split("'");
 
 $t.removeAttr("href");
 $t.removeAttr("onclick");
 $t.addClass("addLink");
 $t.attr('link' , splitting[1]);
 $t.attr('onClick' , "");

 $t.click(function() {
 window.opener.Wishlist($t.attr("link"));
 });
 });
 }
 
 if (compare_delete_enabled()){
 $j('a[onClick*=product_compare/remove/]').each(function(){
 
 var $t = $j(this);
 
 var splitting = $t.attr('onClick').toString().split("'");
 
 $t.removeAttr("href");
 $t.addClass("addLink");
 $t.attr('link' , splitting[1]);
 $t.attr('onClick' , "");

 $t.click(function() {
 window.opener.Compare($t.attr("link"));
 refreshComparePopUp();
 });
 });
 }
}

function update(){
 
 $j('div.box.base-mini.mini-cart').attr('id', 'cart_sidebar');
 $j('div.box.base-mini.mini-wishlist').attr('id', 'wishlist_sidebar');
 $j('div.box.base-mini.mini-compare-products').attr('id', 'compare_sidebar');


 if(cart_add_enabled()){
 $j('button[onClick*=cart/add]').each(function() {
 var $t = $j(this);
 var splitting = $t.attr('onClick').toString().split("'");

 $t.attr('link' , splitting[1]);
 $t.attr('onClick' , "");
 $t.attr('addType' , 1);
 $t.removeAttr("onclick");

 });

 if(options_enabled()){
 $j('button[onClick*=?options=cart]').each(function(){
 if (window.location.pathname.split('/').reverse()[1] != 'cart'){
 var $t = $j(this);
 
 var id = $t.nextAll('.add-to').children('a').attr("href").split('/').reverse()[1];
 
 $t.attr('pid' , id);
 $t.attr('onClick' , "");
 $t.attr('addType' , 1.5);
 $t.removeAttr("onclick");
 }
 });
 }

 $j('button[onClick=productAddToCartForm.submit()]').each(function(){
 var $t = $j(this);
 if( $j("#product-options-wrapper").length > 0){
 if(options_enabled()){
 var _pid = $j('fieldset.no-display input[type=hidden],input[name=product],input[value]').attr('value');
 var i = 1;
// while(!IsNumeric(_pid)){
// _pid = $j('fieldset.no-display input[type=hidden],input[name=product],input[value]:eq(i)').attr('value');}

 $t.attr('pid' , _pid);
 $t.attr('onClick' , "");
 $t.attr('addType' , 2);
 $t.removeAttr("onclick");

 }
 }else{
 var _pid = $j('fieldset.no-display input[type=hidden],input[name=product],input[value]').attr('value');
 var i = 1;
 while(!IsNumeric(_pid)){
 _pid = $j('fieldset.no-display input[type=hidden],input[name=product],input[value]:eq(i)').attr('value');}
 
 $t.attr('pid' , _pid);
 $t.attr('onClick' , "");
 $t.attr('addType' , 1);
 $t.removeAttr("onclick");
 $t.attr('link' , $j("#easyajaxproduct_linkurl").attr("value")+"checkout/cart/add/product/"+_pid+"/");

 }
 });
 }

 if(compare_add_enabled()){
 $j('a[href*=catalog/product_compare/add]').each(function(){
 var $t = $j(this);
 link = $t.attr("href");
 $t.removeAttr("href");
 $t.removeAttr("onclick");
 $t.addClass("addLink");

 $t.attr( 'link' , link);
 $t.attr( 'onClick' , '');

 $t.click(function(){
 Compare($t.attr("link"));
 });
 });
 }
 
 if(wishlist_add_enabled()){
 $j('a[href*=wishlist/index/add]').each(function(){
 var $t = $j(this);
 link = $t.attr("href");
 $t.removeAttr("href");
 $t.removeAttr("onclick");
 $t.addClass("addLink");
 $t.attr('link' , link);

 $t.click(function(){
 Wishlist($t.attr("link"));
 });
 });
 }
 
 $j('button[addType=2]').click(function(){
 if(submitFormWithOptions(false) != 1){
 showAll();
 showPopUpLoading();
 cart_opacity_less();
 }
 });

 $j('button[addType=1]').click(function(){
 addProduct($j(this), false);
 });
 $j('button[addType=1.5]').click(function(){
 addProduct($j(this), true);
 });
 $j("#ajax_continue_shopping").click(function(){
 hideAll();
 });
 $j("#ajax_checkout").click(function(){
 window.setLocation($j("#ajax_checkout").attr("dest"));
 });
 
 refreshWishlistLinks();
 refreshCompareLinks();
}

function refreshCompareLinks(){
 if(compare_delete_enabled() || compare_add_to_cart_enabled()){
 $j('button[onclick*=popWin]').each(function(){
 var $t = $j(this);
 var link = $t.attr("onClick");
 var res = link.toString().replace("/'","/eap/1/'");
 
 $t.attr('onClick' , res);


 });
 
 if(compare_delete_enabled()){
 $j('a[href*=catalog/product_compare/remove]').each(function(){
 var $t = $j(this);
 link = $t.attr("href");
 $t.removeAttr("href");
 $t.removeAttr("onclick");
 $t.addClass("addLink");
 
 $t.children("img").removeAttr("onclick");
 
 $t.attr('link' , link);

 $t.click(function(){
 Compare($t.attr('link'));
 });
 });
 }
 if(compare_clear_all_enabled()){
 $j('a[href*=catalog/product_compare/clear]').each(function(){
 var $t = $j(this);
 link = $t.attr("href");
 $t.removeAttr("href");
 $t.addClass("addLink");
 $t.removeAttr("onclick");
 
 $t.attr('link' , link);


 $t.click(function(){
 Compare($t.attr("link"));
 });
 });
 }
 }
}
function refreshWishlistLinks(){
 if(wishlist_delete_enabled()){
 $j('#wishlist_sidebar a[href*=wishlist/index/remove]').each(function(){
 var $t = $j(this);
 link = $t.attr("href");
 $t.removeAttr("href");
 $t.removeAttr("onclick");
 $t.addClass("addLink");

 $t.attr('link' , link);
 
 $t.click(function(){
 WishlistRemove($t.attr("link"));
 });
 });
 }
 
 if(wishlist_add_to_cart_enabled()){
 $j('#wishlist_sidebar a[href*=wishlist/index/cart]').each(function(){
 var $t = $j(this);
 link = $t.attr("href");
 $t.removeAttr("href");
 $t.addClass("addLink");
 $t.attr('link' , link);
 $t.attr('addType', 3);

 });
 $j('a[addType=3]').click(function(){
 addWishlistProduct($j(this).attr("link"));
 });
 }
}

function refreshWishList(msg){
 reponse = msg.replace('<div class="box base-mini mini-wishlist">', '');
 var sidebar = $j("#wishlist_sidebar");
 sidebar.html(reponse);
 wishlist_opacity_more();
}

function refreshCompare(msg){
 reponse = msg.replace('<div class="box base-mini mini-compare-products">', '');
 var sidebar = $j("#compare_sidebar");
 sidebar.html(reponse);
 compare_opacity_more();
}

function refreshComparePopUp(){
 window.location = $j("#easyajaxproduct_linkurl").attr("value")+"catalog/product_compare/index/";
}


function callbacks(xhr, id)
{
 if (xhr.substring(0,5) == "error"){
 var reponse = xhr.replace('error', '');
 showError(reponse);
 }else{
 
 if (id == 1 || id == 6){// add
 hidePopUpLoading();
 
 if (xhr.substring(0,7) == "options"){
 var reponse = xhr.replace('options', '<input type="hidden" id="callbackId" value="'+id+'" />');
 reponse = reponse.replace('<div class="product-info-box"></div>', '');
 $j("#ajaxaddtocart_popup_options_in").html(reponse);
 showPopUpOptions();
 $j("#ajaxaddtocart").css("max-height", height());
 $j("#ajaxaddtocart").css("top", center("ajaxaddtocart_popup_options"));
 }
 else if (xhr.substring(0,5) == "super"){
 showPopUpRedirecting();
 var reponse = xhr.replace('super', '');
 window.location = reponse;
 }
 else if (xhr.substring(0,12) == "configurable"){
 var reponse = xhr.replace('configurable', '<input type="hidden" id="callbackId" value="'+id+'" />');
 reponse = reponse.replace('<div class="product-info-box"></div>', '');
 $j("#ajaxaddtocart_popup_options_in").html(reponse);
 showPopUpOptions();
 $j("#ajaxaddtocart").css("max-height", height());
 $j("#ajaxaddtocart").css("top", center("ajaxaddtocart_popup_options"));
 }
 else if (xhr.substring(0,7) == "grouped"){
 var reponse = xhr.replace('grouped', '<input type="hidden" id="callbackId" value="'+id+'" />');
 reponse = reponse.replace('<div class="product-info-box"></div>', '');
 $j("#ajaxaddtocart_popup_options_in").html(reponse);
 showPopUpOptions();
 $j("#ajaxaddtocart").css("max-height", height());
 $j("#ajaxaddtocart").css("top", center("ajaxaddtocart_popup_options"));
 }
 else if (xhr.substring(0,6) == "bundle"){
 var reponse = xhr.replace('bundle', '<input type="hidden" id="callbackId" value="'+id+'" />');
 reponse = reponse.replace('<div class="product-info-box"></div>', '');
 $j("#ajaxaddtocart_popup_options_in").html(reponse);
 showPopUpOptions();
 $j("#ajaxaddtocart").css("max-height", height());
 $j("#ajaxaddtocart").css("top", center("ajaxaddtocart_popup_options"));
 }
 else{
 showPopUp();
 
 if(id == 6 || $j("#callbackId").attr('value') == 6){
 split = xhr.split('##ajax_splitting##');
 xhr = split[1];
 reponse = split[0].replace('<div class="box base-mini mini-wishlist">', '');
 
 var sidebar = $j("#wishlist_sidebar");
 sidebar.html(reponse);
 wishlist_opacity_more();
 refreshWishlistLinks();
 }
 
 var reponse = xhr.replace('<div id="cart_sidebar" class="box base-mini mini-cart">', '');
 

 var sidebar = $j("#cart_sidebar");

 sidebar.html(correctCart(reponse));
 cart_opacity_more();
 truncateOptions();
 }
 }else{
 nohide = false;
 if (id == 3){// remove
 reponse = xhr.replace('<div id="cart_sidebar" class="box base-mini mini-cart">', '');
 
 var sidebar = $j("#cart_sidebar");
 sidebar.html(correctCart(reponse));
 
 cart_opacity_more();
 
 
 }else if (id == 4){// cancel last delete & navigation
 reponse = xhr.replace('<div id="cart_sidebar" class="box base-mini mini-cart">', '');
 var sidebar = $j("#cart_sidebar");
 sidebar.html(correctCart(reponse));
 
 cart_opacity_more();
 
 }else if (id == 5){// add to wishlist
 hidePopUpLoading();
 var reponse = xhr.split('login-form');
 if (reponse.length > 1){// customer not logged in
 showLoginPopUp();
 }else{// customer logged in
 hideAll();
 refreshWishList(xhr);
 }
 }else if (id == 7){// remove from wishlist
 hidePopUpLoading();
 hideAll();
 refreshWishList(xhr);
 }else if (id == 8){// Compare
 hidePopUpLoading();
 hideAll();
 refreshCompare(xhr);
 }else if (id == 9){// Compare Pop Up
 refreshComparePopUp(xhr);
 }
 }
 $j(".imagezoom").hide();
 }
}

function addProduct(x, options){
 showAll();
 showPopUpLoading();
 
 cart_opacity_less();
 
 if(options){
 var link = $j("#easyajaxproduct_linkurl").attr("value")+"checkout/cart/add/options/1/product/"+x.attr("pid")+"/";
 }else{
 var link = x.attr("link");
 var qty = $j("#qty").attr("value");
 if (!IsNumeric(qty)){
 qty = 1;}
 }
 
 new $j.ajax({
 url: link+"qty/"+qty+"/eap/1/",
 type: "GET",
 dataType: "html",
 success: function(msg){
 callbacks(msg, 1);
 }
 });
}

function addWishlistProduct(x){
 showAll();
 showPopUpLoading();

 cart_opacity_less();
 wishlist_opacity_less();

 new $j.ajax({
 url: x+"eap/1/",
 type: "GET",
 dataType: "html",
 success: function(msg){
 callbacks(msg, 6);
 }
 });
}

function submitFormWithOptions(fromwishlist){
 var productAddToCartForm = new VarienForm('product_addtocart_form');
 if (productAddToCartForm.validator.validate()) {
 hidePopUpOptions();
 showPopUpLoading();
 
 cart_opacity_less();
 
 var ncallback = 1;
 if (fromwishlist == 1){
 ncallback = 6;
 }
 var qty = $j("#qty").value;
 if (!IsNumeric(qty)){
 qty = 1;}
 new $j.ajax({
 url: $j("#easyajaxproduct_linkurl").attr("value")+"checkout/cart/add/qty/"+qty+"/params/1/eap/1/fromwishlist/"+fromwishlist+"/?"+$j('#product_addtocart_form').serialize(),
 type: "GET",
 dataType: "html",
 success: function(msg){
 callbacks(msg, ncallback);
 }
 });
 }else{
 return 1;
 }
}

function Wishlist(x){
 showAll();
 showPopUpLoading();
 
 wishlist_opacity_less();

 new $j.ajax({
 url: x+"eap/1/",
 type: "GET",
 dataType: "html",
 success: function(msg){
 callbacks(msg, 5);
 }
 });
}

function WishlistRemove(url){
 showAll();
 showPopUpLoading();
 
 wishlist_opacity_less();

 new $j.ajax({
 url: url+"eap/1/",
 type: "GET",
 dataType: "html",
 success: function(msg){
 callbacks(msg, 7);
 }
 });
}

function Compare(url){
 showAll();
 showPopUpLoading();
 
 compare_opacity_less();

 new $j.ajax({
 url: url+"eap/1/",
 type: "GET",
 dataType: "html",
 success: function(msg){
 callbacks(msg, 8);
 }
 });
}

function effects_enabled(){
 return ($j("#easyajaxproduct_effects").attr("value") == 1);
}
function options_enabled(){
 return ($j("#easyajaxproduct_options").attr("value") == 1);
}
function module_enabled(){
 return ($j("#easyajaxproduct_active").attr("value") == 1);
}
function confirmation_seconds(){
 if (IsNumeric($j("#easyajaxproduct_time").attr("value"))){
 return $j("#easyajaxproduct_time").attr("value");
 }else{
 return 5;
 }
}

function cart_add_enabled(){
 return ($j("#easyajaxproduct_cart_add").attr("value") == 1);
}
function cart_delete_enabled(){
 return ($j("#easyajaxproduct_cart_delete").attr("value") == 1);
}
function cart_cancel_last_delete_enabled(){
 return ($j("#easyajaxproduct_cart_cancel_last_delete").attr("value") == 1);
}
function cart_zoom_enabled(){
 return ($j("#easyajaxproduct_cart_zoom").attr("value") == 1);
}
function cart_navigation_enabled(){
 return ($j("#easyajaxproduct_cart_navigation").attr("value") == 1);
}


function wishlist_add_enabled(){
 return ($j("#easyajaxproduct_wishlist_add").attr("value") == 1);
}
function wishlist_delete_enabled(){
 return ($j("#easyajaxproduct_wishlist_delete").attr("value") == 1);
}
function wishlist_add_to_cart_enabled(){
 return ($j("#easyajaxproduct_wishlist_add_to_cart").attr("value") == 1);
}


function compare_add_enabled(){
 return ($j("#easyajaxproduct_compare_add").attr("value") == 1);
}
function compare_delete_enabled(){
 return ($j("#easyajaxproduct_compare_delete").attr("value") == 1);
}
function compare_add_to_cart_enabled(){
 return ($j("#easyajaxproduct_compare_add_to_cart").attr("value") == 1);
}
function compare_clear_all_enabled(){
 return ($j("#easyajaxproduct_compare_clear_all").attr("value") == 1);
}
function cart_opacity_less(){
 if(effects_enabled()){
 if (exists('cart_sidebar')){
 new Effect.Opacity('cart_sidebar', { from: 1.0, to: 0.5, duration: 0.5 });
 }
 }
}
function cart_opacity_more(){
 if(effects_enabled()){
 if (exists('cart_sidebar')){
 new Effect.Opacity('cart_sidebar', { from: 0.5, to: 1.0, duration: 0.5 });
 }
 }
}

function wishlist_opacity_less(){
 if(effects_enabled()){
 if (exists('wishlist_sidebar')){
 new Effect.Opacity('wishlist_sidebar', { from: 1.0, to: 0.5, duration: 0.5 });
 }
 }
}
function wishlist_opacity_more(){
 if(effects_enabled()){
 if (exists('wishlist_sidebar')){
 new Effect.Opacity('wishlist_sidebar', { from: 0.5, to: 1.0, duration: 0.5 });
 }
 }
}

function compare_opacity_less(){
 if(effects_enabled()){
 if (exists('compare_sidebar')){
 new Effect.Opacity('compare_sidebar', { from: 1.0, to: 0.5, duration: 0.5 });
 }
 }
}
function compare_opacity_more(){
 if(effects_enabled()){
 if (exists('compare_sidebar')){
 new Effect.Opacity('compare_sidebar', { from: 0.5, to: 1.0, duration: 0.5 });
 }
 }
}

function appear(id){
 $j("#"+id).className=id+"_show";
 if(effects_enabled()){
 Effect.Appear(id);
 }else{
 $j("#"+id).show();
 }
}

function fade(id){
 $j("#"+id).className=id+"_hide";
 if(effects_enabled()){
 Effect.Fade(id);
 }else{
 $j("#"+id).hide();
 }
}

function showPopUpLoading(){
 nohide = true;
 $j("#ajaxaddtocart_popup_loading").className="ajaxaddtocart_popup_loading_show";
 $j("#ajaxaddtocart_popup_loading").show();
}

function hidePopUpLoading(){
 $j("#ajaxaddtocart_popup_loading").className="ajaxaddtocart_popup_loading_hide";
 $j("#ajaxaddtocart_popup_loading").hide();
}

function showPopUp(){
 nohide = false;
 appear('ajaxaddtocart_popup');
 duree = confirmation_seconds();
 t();
}

function showError(err){
 showPopUpLoading()
 appear('ajaxaddtocart_popup_error');
 $j("#ajaxaddtocart_error").html(err);
}

function hidePopUp(){
 fade('ajaxaddtocart_popup');
}


function showPopUpOptions(){
 nohide = true;
 appear('ajaxaddtocart_popup_options'); 
}

function hidePopUpOptions(){
 $j('#ajaxaddtocart_popup_options').hide();
}

function showPopUpRedirecting(){
 nohide = false;
 appear('ajaxaddtocart_popup_redirecting');
}

function showLoginPopUp(){
 appear('ajaxaddtocart_popup_login');
 window.setLocation($j("#easyajaxproduct_linkurl").attr("value")+'/customer/account/login/');
}

function showAll(){
 $j("#ajaxaddtocart").removeClass("ajaxaddtocart_hide");
 $j("#ajaxaddtocart").addClass("ajaxaddtocart_show");
 $j("#ajaxaddtocart").css("left",((width()/2) - 150) + "px");
 $j("#ajaxaddtocart").css("top",((height()/2) - 25) + "px");
 
 $j("#ajaxaddtocart").show();
 showPopUpLoading();
}

function hideAll(){
 if(nohide == false){
 duree = -1;
 hidePopUp();
 fade('ajaxaddtocart');
 }else{
 hidePopUp();
 }
}

function t()
{
 s=duree;
 if(s == -1){
 s=0;
 }
 else if(s == 0)
 {
 hideAll();
 }
 else
 {
 $j("#compteur").html("<small>This popup will close in "+s+" second(s)</small>");
 duree=duree-1;
 window.setTimeout("t();",999);
 }
}

function imageZoom(url, id){
 if (cart_zoom_enabled()){
 arr_images = url.split('#');
 arr_images_index = 0;
 z=$j("#imagezoom"+id);
 z.show();
 }
}

function imageZoomNext(id){
 if (cart_zoom_enabled()){
 if(arr_images_index + 1 == arr_images.length){
 arr_images_index = 0;
 }else{
 arr_images_index = arr_images_index + 1;
 }
 z=$j("#imagezoom"+id);
 z.html('<img style="width:100%" src="'+arr_images[arr_images_index]+'" />');
 }
}
function imageZoomPrevious(id){
 if (cart_zoom_enabled()){
 if(arr_images_index == 0){
 arr_images_index = arr_images.length - 1;
 }else{
 arr_images_index = arr_images_index - 1;
 }
 z=$j("#imagezoom"+id);
 z.html('<img style="width:100%" src="'+arr_images[arr_images_index]+'" />');
 }
}
function imageZoomKill(id){
 if (cart_zoom_enabled()){
 z=$j("#imagezoom"+id);
 z.hide();
 }
}
function center(id){
 return (height()/2)-($j("#"+id).height()/2);
}

function height() {
 var myHeight = 0;
 if( typeof( window.innerWidth ) == 'number' ) {
 // Non-IE
 myHeight = window.innerHeight;
 } else if( document.documentElement && ( document.documentElement.clientHeight ) ) {
 // IE 6+ in 'standards compliant mode'
 myHeight = document.documentElement.clientHeight;
 } else if( document.body && (document.body.clientHeight ) ) {
 // IE 4 compatible
 myHeight = document.body.clientHeight;
 }
 return myHeight;
}

function width() {
 var myWidth = 0;
 if( typeof( window.innerWidth ) == 'number' ) {
 // Non-IE
 myWidth = window.innerWidth;
 } else if( document.documentElement && ( document.documentElement.clientWidth ) ) {
 // IE 6+ in 'standards compliant mode'
 myWidth = document.documentElement.clientWidth;
 } else if( document.body && (document.body.clientWidth ) ) {
 // IE 4 compatible
 myWidth = document.body.clientWidth;
 }
 return myWidth;
}

function IsNumeric(input)
{
 return (input - 0) == input && input.length > 0;
}

function exists(id){
 return ( $j("#"+id).length > 0 );
}

var xob = false;
function inComparePopUp(){
 if(xob){
 return false;
 }
 xob=true;

 if(window.opener != null){
 var lo = window.location;
 var splitted = lo.toString().split("/");
 var i =0;
 while( i < splitted.length ){
 if(splitted[i] == 'product_compare'){
 return true;
 }
 i++;
 }
 }
 return false;
}


function extractId(url){
 t = url.split('/');
 next = false;
 
 for (i in t){
 if(next){
 return t[i];
 }
 if(t[i]== 'item'){
 next = true;
 }
 }
}


function gup(name)
{
 name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
 var regexS = "[\\?&]"+name+"=([^&#]*)";
 var regex = new RegExp( regexS );
 var results = regex.exec( window.location.href );
 if( results == null )
 return "";
 else
 return results[1];
}

function correctCart(a)
{
 var rep = a.substr(0, a.length-64);
 return rep + '<script type="text/javascript">truncateOptions();</script>';
}

function ajaxError(url){
 window.location = url;
}
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @copyright Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 */
if(typeof Product=='undefined') {
 var Product = {};
}

/********************* IMAGE ZOOMER ***********************/

Product.Zoom = Class.create();
/**
 * Image zoom control
 *
 * @author Magento Core Team <core@magentocommerce.com>
 */
Product.Zoom.prototype = {
 initialize: function(imageEl, trackEl, handleEl, zoomInEl, zoomOutEl, hintEl){
 this.containerEl = $(imageEl).parentNode;
 this.imageEl = $(imageEl);
 this.handleEl = $(handleEl);
 this.trackEl = $(trackEl);
 this.hintEl = $(hintEl);

 this.containerDim = Element.getDimensions(this.containerEl);
 this.imageDim = Element.getDimensions(this.imageEl);

 this.imageDim.ratio = this.imageDim.width/this.imageDim.height;

 this.floorZoom = 1;

 if (this.imageDim.width > this.imageDim.height) {
 this.ceilingZoom = this.imageDim.width / this.containerDim.width;
 } else {
 this.ceilingZoom = this.imageDim.height / this.containerDim.height;
 }

 if (this.imageDim.width <= this.containerDim.width
 && this.imageDim.height <= this.containerDim.height) {
 this.trackEl.up().hide();
 this.hintEl.hide();
 this.containerEl.removeClassName('product-image-zoom');
 return;
 }

 this.imageX = 0;
 this.imageY = 0;
 this.imageZoom = 1;

 this.sliderSpeed = 0;
 this.sliderAccel = 0;
 this.zoomBtnPressed = false;

 this.showFull = false;

 this.selects = document.getElementsByTagName('select');

 this.draggable = new Draggable(imageEl, {
 starteffect:false,
 reverteffect:false,
 endeffect:false,
 snap:this.contain.bind(this)
 });

 this.slider = new Control.Slider(handleEl, trackEl, {
 axis:'horizontal',
 minimum:0,
 maximum:Element.getDimensions(this.trackEl).width,
 alignX:0,
 increment:1,
 sliderValue:0,
 onSlide:this.scale.bind(this),
 onChange:this.scale.bind(this)
 });

 this.scale(0);

 Event.observe(this.imageEl, 'dblclick', this.toggleFull.bind(this));

 Event.observe($(zoomInEl), 'mousedown', this.startZoomIn.bind(this));
 Event.observe($(zoomInEl), 'mouseup', this.stopZooming.bind(this));
 Event.observe($(zoomInEl), 'mouseout', this.stopZooming.bind(this));

 Event.observe($(zoomOutEl), 'mousedown', this.startZoomOut.bind(this));
 Event.observe($(zoomOutEl), 'mouseup', this.stopZooming.bind(this));
 Event.observe($(zoomOutEl), 'mouseout', this.stopZooming.bind(this));
 },

 toggleFull: function () {
 this.showFull = !this.showFull;
 //TODO: hide selects for IE only

 for (i=0; i<this.selects.length; i++) {
 this.selects[i].style.visibility = this.showFull ? 'hidden' : 'visible';
 }
 val_scale = !this.showFull ? this.slider.value : 1;
 this.scale(val_scale);

 this.trackEl.style.visibility = this.showFull ? 'hidden' : 'visible';
 this.containerEl.style.overflow = this.showFull ? 'visible' : 'hidden';
 this.containerEl.style.zIndex = this.showFull ? '1000' : '9';

 return this;
 },

 scale: function (v) {

 var centerX = (this.containerDim.width*(1-this.imageZoom)/2-this.imageX)/this.imageZoom;
 var centerY = (this.containerDim.height*(1-this.imageZoom)/2-this.imageY)/this.imageZoom;

 this.imageZoom = this.floorZoom+(v*(this.ceilingZoom-this.floorZoom));

 this.imageEl.style.width = (this.imageZoom*this.containerDim.width)+'px';
 if(this.containerDim.ratio){
 this.imageEl.style.height = (this.imageZoom*this.containerDim.width*this.containerDim.ratio)+'px'; // for safari
 }

 this.imageX = this.containerDim.width*(1-this.imageZoom)/2-centerX*this.imageZoom;
 this.imageY = this.containerDim.height*(1-this.imageZoom)/2-centerY*this.imageZoom;

 this.contain(this.imageX, this.imageY, this.draggable);

 return true;
 },

 startZoomIn: function()
 {
 this.zoomBtnPressed = true;
 this.sliderAccel = .002;
 this.periodicalZoom();
 this.zoomer = new PeriodicalExecuter(this.periodicalZoom.bind(this), .05);
 return this;
 },

 startZoomOut: function()
 {
 this.zoomBtnPressed = true;
 this.sliderAccel = -.002;
 this.periodicalZoom();
 this.zoomer = new PeriodicalExecuter(this.periodicalZoom.bind(this), .05);
 return this;
 },

 stopZooming: function()
 {
 if (!this.zoomer || this.sliderSpeed==0) {
 return;
 }
 this.zoomBtnPressed = false;
 this.sliderAccel = 0;
 },

 periodicalZoom: function()
 {
 if (!this.zoomer) {
 return this;
 }

 if (this.zoomBtnPressed) {
 this.sliderSpeed += this.sliderAccel;
 } else {
 this.sliderSpeed /= 1.5;
 if (Math.abs(this.sliderSpeed)<.001) {
 this.sliderSpeed = 0;
 this.zoomer.stop();
 this.zoomer = null;
 }
 }
 this.slider.value += this.sliderSpeed;

 this.slider.setValue(this.slider.value);
 this.scale(this.slider.value);

 return this;
 },

 contain: function (x,y,draggable) {

 var dim = Element.getDimensions(draggable.element);

 var xMin = 0, xMax = this.containerDim.width-dim.width;
 var yMin = 0, yMax = this.containerDim.height-dim.height;

 x = x>xMin ? xMin : x;
 x = x<xMax ? xMax : x;
 y = y>yMin ? yMin : y;
 y = y<yMax ? yMax : y;

 this.imageX = x;
 this.imageY = y;

 this.imageEl.style.left = this.imageX+'px';
 this.imageEl.style.top = this.imageY+'px';

 return [x,y];
 }
}

/**************************** CONFIGURABLE PRODUCT **************************/
Product.Config = Class.create();
Product.Config.prototype = {
 initialize: function(config){
 this.config = config;
 this.taxConfig = this.config.taxConfig;
 this.settings = $$('.super-attribute-select');
 this.state = new Hash();
 this.priceTemplate = new Template(this.config.template);
 this.prices = config.prices;

 this.settings.each(function(element){
 Event.observe(element, 'change', this.configure.bind(this))
 }.bind(this));

 // fill state
 this.settings.each(function(element){
 var attributeId = element.id.replace(/[a-z]*/, '');
 if(attributeId && this.config.attributes[attributeId]) {
 element.config = this.config.attributes[attributeId];
 element.attributeId = attributeId;
 this.state[attributeId] = false;
 }
 }.bind(this))

 // Init settings dropdown
 var childSettings = [];
 for(var i=this.settings.length-1;i>=0;i--){
 var prevSetting = this.settings[i-1] ? this.settings[i-1] : false;
 var nextSetting = this.settings[i+1] ? this.settings[i+1] : false;
 if(i==0){
 this.fillSelect(this.settings[i])
 }
 else {
 this.settings[i].disabled=true;
 }
 $(this.settings[i]).childSettings = childSettings.clone();
 $(this.settings[i]).prevSetting = prevSetting;
 $(this.settings[i]).nextSetting = nextSetting;
 childSettings.push(this.settings[i]);
 }

 // try retireve options from url
 var separatorIndex = window.location.href.indexOf('#');
 if (separatorIndex!=-1) {
 var paramsStr = window.location.href.substr(separatorIndex+1);
 this.values = paramsStr.toQueryParams();
 this.settings.each(function(element){
 var attributeId = element.attributeId;
 element.value = this.values[attributeId];
 this.configureElement(element);
 }.bind(this));
 }
 },

 configure: function(event){
 var element = Event.element(event);
 this.configureElement(element);
 },

 configureElement : function(element) {
 this.reloadOptionLabels(element);
 if(element.value){
 this.state[element.config.id] = element.value;
 if(element.nextSetting){
 element.nextSetting.disabled = false;
 this.fillSelect(element.nextSetting);
 this.resetChildren(element.nextSetting);
 }
 }
 else {
 this.resetChildren(element);
 }
 this.reloadPrice();
// Calculator.updatePrice();
 },

 reloadOptionLabels: function(element){
 var selectedPrice;
 if(element.options[element.selectedIndex].config){
 selectedPrice = parseFloat(element.options[element.selectedIndex].config.price)
 }
 else{
 selectedPrice = 0;
 }
 for(var i=0;i<element.options.length;i++){
 if(element.options[i].config){
 element.options[i].text = this.getOptionLabel(element.options[i].config, element.options[i].config.price-selectedPrice);
 }
 }
 },

 resetChildren : function(element){
 if(element.childSettings) {
 for(var i=0;i<element.childSettings.length;i++){
 element.childSettings[i].selectedIndex = 0;
 element.childSettings[i].disabled = true;
 if(element.config){
 this.state[element.config.id] = false;
 }
 }
 }
 },

 fillSelect: function(element){
 var attributeId = element.id.replace(/[a-z]*/, '');
 var options = this.getAttributeOptions(attributeId);
 this.clearSelect(element);
 element.options[0] = new Option(this.config.chooseText, '');

 var prevConfig = false;
 if(element.prevSetting){
 prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];
 }

 if(options) {
 var index = 1;
 for(var i=0;i<options.length;i++){
 var allowedProducts = [];
 if(prevConfig) {
 for(var j=0;j<options[i].products.length;j++){
 if(prevConfig.config.allowedProducts
 && prevConfig.config.allowedProducts.indexOf(options[i].products[j])>-1){
 allowedProducts.push(options[i].products[j]);
 }
 }
 } else {
 allowedProducts = options[i].products.clone();
 }

 if(allowedProducts.size()>0){
 options[i].allowedProducts = allowedProducts;
 element.options[index] = new Option(this.getOptionLabel(options[i], options[i].price), options[i].id);
 element.options[index].config = options[i];
 index++;
 }
 }
 }
 },

 getOptionLabel: function(option, price){
 var price = parseFloat(price);
 if (this.taxConfig.includeTax) {
 var tax = price / (100 + this.taxConfig.defaultTax) * this.taxConfig.defaultTax;
 var excl = price - tax;
 var incl = excl*(1+(this.taxConfig.currentTax/100));
 } else {
 var tax = price * (this.taxConfig.currentTax / 100);
 var excl = price;
 var incl = excl + tax;
 }

 if (this.taxConfig.showIncludeTax || this.taxConfig.showBothPrices) {
 price = incl;
 } else {
 price = excl;
 }

 var str = option.label;
 if(price){
 if (this.taxConfig.showBothPrices) {
 str+= ' ' + this.formatPrice(excl, true) + ' (' + this.formatPrice(price, true) + ' ' + this.taxConfig.inclTaxTitle + ')';
 } else {
 str+= ' ' + this.formatPrice(price, true);
 }
 }
 return str;
 },

 formatPrice: function(price, showSign){
 var str = '';
 price = parseFloat(price);
 if(showSign){
 if(price<0){
 str+= '-';
 price = -price;
 }
 else{
 str+= '+';
 }
 }

 var roundedPrice = (Math.round(price*100)/100).toString();

 if (this.prices && this.prices[roundedPrice]) {
 str+= this.prices[roundedPrice];
 }
 else {
 str+= this.priceTemplate.evaluate({price:price.toFixed(2)});
 }
 return str;
 },

 clearSelect: function(element){
 for(var i=element.options.length-1;i>=0;i--){
 element.remove(i);
 }
 },

 getAttributeOptions: function(attributeId){
 if(this.config.attributes[attributeId]){
 return this.config.attributes[attributeId].options;
 }
 },

 reloadPrice: function(){
 var price = 0;
 for(var i=this.settings.length-1;i>=0;i--){
 var selected = this.settings[i].options[this.settings[i].selectedIndex];
 if(selected.config){
 price += parseFloat(selected.config.price);
 }
 }

 optionsPrice.changePrice('config', price);
 optionsPrice.reload();

 return price;

 if($('product-price-'+this.config.productId)){
 $('product-price-'+this.config.productId).innerHTML = price;
 }
 this.reloadOldPrice();
 },

 reloadOldPrice: function(){
 if ($('old-price-'+this.config.productId)) {

 var price = parseFloat(this.config.oldPrice);
 for(var i=this.settings.length-1;i>=0;i--){
 var selected = this.settings[i].options[this.settings[i].selectedIndex];
 if(selected.config){
 price+= parseFloat(selected.config.price);
 }
 }
 if (price < 0)
 price = 0;
 price = this.formatPrice(price);

 if($('old-price-'+this.config.productId)){
 $('old-price-'+this.config.productId).innerHTML = price;
 }

 }
 }
}


/**************************** SUPER PRODUCTS ********************************/

Product.Super = {};
Product.Super.Configurable = Class.create();

Product.Super.Configurable.prototype = {
 initialize: function(container, observeCss, updateUrl, updatePriceUrl, priceContainerId) {
 this.container = $(container);
 this.observeCss = observeCss;
 this.updateUrl = updateUrl;
 this.updatePriceUrl = updatePriceUrl;
 this.priceContainerId = priceContainerId;
 this.registerObservers();
 },
 registerObservers: function() {
 var elements = this.container.getElementsByClassName(this.observeCss);
 elements.each(function(element){
 Event.observe(element, 'change', this.update.bindAsEventListener(this));
 }.bind(this));
 return this;
 },
 update: function(event) {
 var elements = this.container.getElementsByClassName(this.observeCss);
 var parameters = Form.serializeElements(elements, true);

 new Ajax.Updater(this.container, this.updateUrl + '?ajax=1', {
 parameters:parameters,
 onComplete:this.registerObservers.bind(this)
 });
 var priceContainer = $(this.priceContainerId);
 if(priceContainer) {
 new Ajax.Updater(priceContainer, this.updatePriceUrl + '?ajax=1', {
 parameters:parameters
 });
 }
 }
}

/**************************** PRICE RELOADER ********************************/
Product.OptionsPrice = Class.create();
Product.OptionsPrice.prototype = {
 initialize: function(config) {
 this.productId = config.productId;
 this.priceFormat = config.priceFormat;
 this.includeTax = config.includeTax;
 this.defaultTax = config.defaultTax;
 this.currentTax = config.currentTax;
 this.productPrice = config.productPrice;
 this.showIncludeTax = config.showIncludeTax;
 this.showBothPrices = config.showBothPrices;
 this.productPrice = config.productPrice;
 this.productOldPrice = config.productOldPrice;
 this.skipCalculate = config.skipCalculate;
 this.duplicateIdSuffix = config.idSuffix;

 this.oldPlusDisposition = config.oldPlusDisposition;
 this.plusDisposition = config.plusDisposition;

 this.oldMinusDisposition = config.oldMinusDisposition;
 this.minusDisposition = config.minusDisposition;

 this.optionPrices = {};
 this.containers = {};

 this.displayZeroPrice = true;

 this.initPrices();
 },

 setDuplicateIdSuffix: function(idSuffix) {
 this.duplicateIdSuffix = idSuffix;
 },

 initPrices: function() {
 this.containers[0] = 'product-price-' + this.productId;
 this.containers[1] = 'bundle-price-' + this.productId;
 this.containers[2] = 'price-including-tax-' + this.productId;
 this.containers[3] = 'price-excluding-tax-' + this.productId;
 this.containers[4] = 'old-price-' + this.productId;
 },

 changePrice: function(key, price) {
 this.optionPrices[key] = parseFloat(price);
 },

 getOptionPrices: function() {
 var result = 0;
 var nonTaxable = 0;
 $H(this.optionPrices).each(function(pair) {
 if (pair.key == 'nontaxable') {
 nonTaxable = pair.value;
 } else {
 result += pair.value;
 }
 });
 var r = new Array(result, nonTaxable);
 return r;
 },

 reload: function() {
 var price;
 var formattedPrice;
 var optionPrices = this.getOptionPrices();
 var nonTaxable = optionPrices[1];
 optionPrices = optionPrices[0];
 $H(this.containers).each(function(pair) {
 var _productPrice;
 var _plusDisposition;
 var _minusDisposition;
 if ($(pair.value)) {
 if (pair.value == 'old-price-'+this.productId && this.productOldPrice != this.productPrice) {
 _productPrice = this.productOldPrice;
 _plusDisposition = this.oldPlusDisposition;
 _minusDisposition = this.oldMinusDisposition;
 } else {
 _productPrice = this.productPrice;
 _plusDisposition = this.plusDisposition;
 _minusDisposition = this.minusDisposition;
 }

 var price = optionPrices+parseFloat(_productPrice)
 if (this.includeTax == 'true') {
 // tax = tax included into product price by admin
 var tax = price / (100 + this.defaultTax) * this.defaultTax;
 var excl = price - tax;
 var incl = excl*(1+(this.currentTax/100));
 } else {
 var tax = price * (this.currentTax / 100);
 var excl = price;
 var incl = excl + tax;
 }

 excl += parseFloat(_plusDisposition);
 incl += parseFloat(_plusDisposition);
 excl -= parseFloat(_minusDisposition);
 incl -= parseFloat(_minusDisposition);

 //adding nontaxlable part of options
 excl += parseFloat(nonTaxable);
 incl += parseFloat(nonTaxable);

 if (pair.value == 'price-including-tax-'+this.productId) {
 price = incl;
 } else if (pair.value == 'old-price-'+this.productId) {
 if (this.showIncludeTax || this.showBothPrices) {
 price = incl;
 } else {
 price = excl;
 }
 } else {
 if (this.showIncludeTax) {
 price = incl;
 } else {
 if (!this.skipCalculate || _productPrice == 0) {
 price = excl;
 } else {
 price = optionPrices+parseFloat(_productPrice);
 }
 }
 }

 if (price < 0) price = 0;

 if (price > 0 || this.displayZeroPrice) {
 formattedPrice = this.formatPrice(price);
 } else {
 formattedPrice = '';
 }

 if ($(pair.value).select('.price')[0]) {
 $(pair.value).select('.price')[0].innerHTML = formattedPrice;
 if ($(pair.value+this.duplicateIdSuffix) && $(pair.value+this.duplicateIdSuffix).select('.price')[0]) {
 $(pair.value+this.duplicateIdSuffix).select('.price')[0].innerHTML = formattedPrice;
 }
 } else {
 $(pair.value).innerHTML = formattedPrice;
 if ($(pair.value+this.duplicateIdSuffix)) {
 $(pair.value+this.duplicateIdSuffix).innerHTML = formattedPrice;
 }
 }
 };
 }.bind(this));
 },
 formatPrice: function(price) {
 return formatCurrency(price, this.priceFormat);
 }
}

