var BYMN = BYMN || {};

jQuery.noConflict();


/*
* Beymen Default values for global usage.
*/
BYMN.defaultVars = {
	
	isAnimate : [],
	// For callBack control i need a null function.
	nullFunc : function() {},
	cache : []
};

/*
* this function added hvr clas to navigation list items (li).
*/
BYMN.createNavMenu = function() {
	jQuery('#nav>li').hover(function() {
        jQuery(this).addClass('hvr');
    },
    function() {
        jQuery(this).removeClass('hvr');
    });
    
    jQuery('#foMenu ul > li').hover(function() {
        jQuery(this).addClass('hvr');
    },
    function() {
        jQuery(this).removeClass('hvr');
    });
}

/*
* Beymen global cookie function get - set and delete
*/
BYMN.cookie = {
    get : function (name) {
        var start = document.cookie.indexOf( name + "=" );
    	var len = start + name.length + 1;
    	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
    		return null;
    	}
    	if ( start == -1 ) return null;
    	var end = document.cookie.indexOf( ';', len );
    	if ( end == -1 ) end = document.cookie.length;
    	return unescape( document.cookie.substring( len, end ) );
    },
    set : function (name, value, expires, path, domain, secure) {
    	var today = new Date();
    	today.setTime( today.getTime() );
    	if ( expires ) {
    		expires = expires * 1000 * 60 * 60 * 24;
    	}
    	var expires_date = new Date( today.getTime() + (expires) );
    	document.cookie = name+'='+escape( value ) +
    		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
    		( ( path ) ? ';path=' + path : '' ) +
    		( ( domain ) ? ';domain=' + domain : '' ) +
    		( ( secure ) ? ';secure' : '' );
    },
    del : function (name, path, domain) {
    	if ( BYMN.cookie.get( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
    }
};

/*
* Up and down animation for beymen homepage newsletter block
* Create - up and down functions
*/
BYMN.animateNews = {
	currentNews : 0,
	create : function() {
		jQuery('#newsButtons a.next').bind('click', function() {
			BYMN.animateNews.down();
		});
		jQuery('#newsButtons a.prev').bind('click', function() {
			BYMN.animateNews.up();
		});
	},
	up : function() {
		if(BYMN.animateNews.currentNews < (jQuery('#newsRight ul li').length - 1)) {
			BYMN.animateNews.currentNews++;
			jQuery('#newsRight ul').animate({marginTop : '-=95px'}, 500);
		}
	},
	down : function() {
		if(BYMN.animateNews.currentNews > 0) {
			BYMN.animateNews.currentNews--;
			jQuery('#newsRight ul').animate({marginTop : '+=95px'}, 500);
		}
	}
}



/*************************************************** 
 * 
 * BEYMEN MessageBox Object
 * 
 ***************************************************/

BYMN.messageBox = {
    get : function(txt, closeFunc) {
        var obj = this;
        //var callBack = closeFunc || nullFunc;
        if(!this.inUse) {
            var bck = document.createElement('div');
                bck.id = "blackBack";
            document.body.appendChild(bck);
            var msg = document.createElement('div');
                msg.id = "popMsg";
            var closeBtn = document.createElement('a');
                closeBtn.id = "closeMsg";
            msg.innerHTML = txt;
            msg.appendChild(closeBtn);
            document.body.appendChild(msg);
            
            jQuery('#closeMsg, #blackBack').click(function(evt){
              obj.close(closeFunc);
            });
            this.inUse = true;
            msg.style.marginTop = (-1 * Math.floor(msg.offsetHeight/2)) + "px";
            msg.style.marginLeft = (-1 * Math.floor(msg.offsetWidth/2)) + "px";
            
            bck.style.height = document.body.offsetHeight ;
            
        }
    },
    close : function(func) {
        //var callBack = func || nullFunc;
        document.body.removeChild(document.getElementById('blackBack'));
        document.body.removeChild(document.getElementById('popMsg'));
        this.inUse = false;
        if(typeof(func) == 'function') func();
    },
    inUse : false
};
/****************************************************/


/*************************************************** 
 * 
 * BEYMEN Image Gallery  Plugin
 * 
 ***************************************************/
;(function($){
  BYMN.imageGallery = function(object, options) {
    this.object   = object;
    this.options  = options;
    this.bindEvents();
    var firstGalleryItem = $(this.options.galleryItem).eq(0);
    this.setAsSelected(firstGalleryItem);
    this.currentItemIndex = 0;
  }

  BYMN.imageGallery.defaults = {
    galleryItem : '.gallery-item',
    bigImage    : '#img_bigImage',
    upButton    : '#media_up',
    downButton  : '#media_down'
  }

  BYMN.imageGallery.prototype = {
    bindEvents : function() {
      var obj = this;
      
      $(obj.options.galleryItem).find('a').click(function() {
        var galleryItem = $(this).parent();
        obj.setAsSelected(galleryItem);
        return false;
      });
      
      $(obj.options.upButton).click(function() {
        obj.prev();
      });
      
      $(obj.options.downButton).click(function() {
        obj.next();
      });
     },
     
     setAsSelected : function(galleryItem) {
       var imageUrl = $(galleryItem).find('a').attr('href');
       $(this.options.bigImage).attr('src', imageUrl);
       $(this.options.galleryItem).find('img').animate({opacity:0.25}, 100);
       $(galleryItem).find('img').animate({opacity:1});
       this.currentItemIndex = $(this.options.galleryItem).index(galleryItem);
     },
     
     getItemCount : function() {
       return $(this.options.galleryItem).length;
     },
     
     next : function() {
       if(this.currentItemIndex >= this.getItemCount() -1) return false;
       var galleryItem = $(this.options.galleryItem).eq(this.currentItemIndex + 1);
       this.setAsSelected(galleryItem);
       return true;
     },
     
     prev : function() {
       if(this.currentItemIndex <= 0) return false;
       var galleryItem = $(this.options.galleryItem).eq(this.currentItemIndex - 1);
       this.setAsSelected(galleryItem);
       return true;
     }
  }
  
  $.fn.extend({
    imageGallery : function(options) {
      return this.each(function() {
        var opt = $.extend({}, BYMN.imageGallery.defaults, options);
        new BYMN.imageGallery(this, opt);
      });
    }
  })
})(jQuery)
/****************************************************/

/*************************************************** 
 * 
 * BEYMEN ajaxLink  Plugin
 * 
 ***************************************************/
;(function($){
  BYMN.AjaxLink = function(object, options) {
    this.object = object;
    this.options = options;
    this.initialize();
  }
  
  BYMN.AjaxLink.defaults = {
    type      : 'GET',
    dataType  : 'text',
    cache     : true,
    notAjax   : false,
    noMargin  : false
  }
  
  BYMN.AjaxLink.prototype = {
    getUrl : function(object) {
      return $(object).attr('href');
    },
    
    load : function(url) {
      var obj = this;
      if(obj.options.notAjax) {
          BYMN.messageBox.get($(url).html());
          if(obj.options.noMargin) {
              $('#popMsg').css('margin-top', '-150px');
          }
      } else {
          $.ajax({
            type      : obj.options.type,
            dataType  : obj.options.dataType,
            cache     : obj.options.cache,
            url       : url,
            success   : function(data, textStatus) {
              if(textStatus == 'success') BYMN.messageBox.get(data);
            }
          });
      }
    },
    
    initialize : function() {
      var obj = this;
      $(this.object).click(function(e) {
        e.preventDefault();
        var linkUrl = obj.getUrl(this);
        obj.load(linkUrl);
        return false;
      });
    }
  }
  
  $.fn.extend({
    ajaxLink : function(options) {
      return this.each(function() {
        var opt = $.extend({}, BYMN.AjaxLink.defaults, options);
        new BYMN.AjaxLink(this, opt);
      });
    }
  });
})(jQuery)
/****************************************************/

/*************************************************** 
 * 
 * BEYMEN tabControl Plugin
 * 
 ***************************************************/
 ;(function($) {
   BYMN.TabControl = function(object, options) {
     this.object = object;
     this.options = options;
     this.initialize();
   }
   
   BYMN.TabControl.prototype = {
     initialize : function() {
      var firstLinkObject = $(this.object).find(this.options.linkList).find('li a').eq(0);
      this.setAsSelected(firstLinkObject);
      this.bindLinkEvents();
     },
     
     bindLinkEvents : function() {
       var obj = this;
       $(this.options.linkList).find('li a').click(function() {
         obj.setAsSelected(this);
         return false;
       });
     },
     
     setAsSelected : function(linkObject) {
       var linkHref = $(linkObject).attr('href');
       $(this.object).find(this.options.linkList).find('li a').removeClass('selected');
       $(linkObject).addClass('selected');
       $(this.object).find(this.options.tabContentContainer).hide();
       $(this.object).find(linkHref).show();
     }
   }
   
   BYMN.TabControl.defaults = {
     linkList             : '.tab-control-links',
     tabContentContainer  : '.tab-control-content'
   }
   
   $.fn.extend({
     tabControl : function(options) {
       return this.each(function() {
         var opt = $.extend({}, BYMN.TabControl.defaults, options);
         new BYMN.TabControl(this, opt);
       });
     }
   })
 })(jQuery)
/****************************************************/

/*************************************************** 
 * 
 * BEYMEN horizontalSlider
 * 
 ***************************************************/
;
(function($) {
  BYMN.HorizontalSlider = function(object, options) {
    this.object = object;
    this.options = options;
    this.initialize();
    this.busy = false;
  }

  BYMN.HorizontalSlider.prototype = {
    initialize : function() {
      var obj = this;

      //setting left/right button visibilitiy.
      var capsuleWidth    = this.getCapsule().width();
      var collectionWidth = this.getCollection().width(); 
      
      if( collectionWidth > capsuleWidth ) {
        this.showButtons(false);
      } else {
        this.showButtons(true);
      }

      //binding button events.
      $(this.object).find(this.options.leftButton).click(function() {
        obj.slideLeft();
      });

      $(this.object).find(this.options.rightButton).click(function() {
        obj.slideRight();
      });
      
      
    },
    
    showButtons : function(bStatus) {
      if(bStatus) {
        $(this.object).find(this.options.leftButton).show();
        $(this.object).find(this.options.rightButton).show();
      } else {
        $(this.object).find(this.options.leftButton).hide();
        $(this.object).find(this.options.rightButton).hide();
      }
        
    },

    slideRight : function() {
      if(this.busy) return false;
      if( this.getCollectionItem( this.getCollection().children().length-1).position().left == 0 ) return false;
      var obj = this;
      var stepSize = this.getCollectionItem(0).width();
      this.busy = true;
      this.getCollection().animate({
        left : '-=' + (stepSize + this.options.itemMargin)
      }, this.options.sliderInterval, function() {
        obj.busy = false;
      });
      return true;
    },

    slideLeft : function() {
      if(this.busy) return false;
      if(this.getCollection().position().left == 0) return false;
      
      var obj = this;
      var stepSize = this.getCollectionItem(0).width();
      this.busy = true;
      this.getCollection().animate({
        left : '+=' + (stepSize + this.options.itemMargin)
      }, this.options.sliderInterval, function() {
        obj.busy = false;
      });
      return true;
    },

    getCapsule : function() {
      return $(this.object).find(this.options.collectionCapsule);
    },

    getCollection: function() {
      return this.getCapsule().children().eq(0);
      },
      
    getCollectionItem : function(itemIndex) {
      return this.getCollection().children().eq(itemIndex);
    }
  }


  BYMN.HorizontalSlider.defaults = {
    leftButton          : '.hslider-left-button',
    rightButton         : '.hslider-right-button',
    collectionCapsule   : '.hslider-collection-capsule',
    itemMargin          : 4,
    sliderInterval      : 250
  }

  $.fn.extend({
    horizontalSlider : function(options) {
      return this.each(function() {
        var opt = $.extend({}, BYMN.HorizontalSlider.defaults, options);
        new BYMN.HorizontalSlider(this, opt);
      });
    }
  })
})(jQuery)
/****************************************************/

BYMN.setTopMenu = function(){
	jQuery('#loginTop').append('<form id="header_login_form" method="post" action="'+mainUrl+'customer/account/loginPost/"><div id="login">' +
		'<h1><a href="javascript:;" onClick="jQuery(\'#login\').toggle()"><img src="'+ mainTemplateUrl +'images/login.jpg" border="0"/></a></h1>' +
		'<table cellpadding="0" cellspacing="0" border="0">' +
		'  <tr>' +
		'    <td valign="bottom"><img src="/skin/frontend/default/beymen_v2/images/email.jpg" border="0" /></td>' +
		'  </tr>' +
		'  <tr>' +
		'    <td class="eMail"><input id="email" class="input-text required-entry validate-email" type="text" title="Email Adresiniz" value="" name="login[username]" /></td>' +
		'  </tr>' +
		'  <tr>' +
		'    <td valign="bottom"><img src="'+ mainTemplateUrl +'images/sifre.jpg" border="0" /></td>' +
		'  </tr>' +
		'  <tr>' +
		'    <td class="password"><input id="pass" class="input-text required-entry validate-newPass" type="password" title="Şifre" name="login[password]" /></td>' +
		'  </tr>' +
		'</table>' +
		'<p class="forgotPassword"><a href="' + mainUrl + 'customer/account/forgotpassword/">Şifremi Unuttum</a></p>' +
		'<a id="topLoginSubmit" href="javascript:;"><img src="'+ mainTemplateUrl +'images/giris.jpg" border="0" /></a>' +
		'</div></form>').children('a').click(function(e) {
			e.preventDefault();
			jQuery('#login').toggle();
      
      jQuery('#topLoginSubmit').unbind('click').click(function(e) {
        e.preventDefault();
        jQuery('#header_login_form').submit();
      });
	  
	  jQuery('#pass').unbind('keydown').keydown(function(e) {
	  	if(e.keyCode == "13") {
			e.preventDefault();
			jQuery('#header_login_form').submit();
		}
	  });
	});
	
	jQuery('#pochetteTop').append('<div id="pochetteHover" class="clearFix">' +
		'<h1><a href="javascript:;" onClick="jQuery(\'#pochetteHover\').toggle()"><img src="'+ mainTemplateUrl +'images/pochetteHover.jpg" border="0" /></a></h1>' +
		'<div id="myPochette"><a href="javascript:;" class="animateTop"></a>' +
		'  <table id="headerCart" cellpadding="0" cellspacing="0" border="0">' +
		'  </table>' +
		'  <a href="javascript:;" class="animateDown"></a> </div>' +
		'<p class="total">Toplam <span id="itemCount">0</span> parça: <span class="price" id="totalPrice">0.00 TL</span></p>' +
		'<div id="decide"><a href="javascript:;" class="close"></a> <a href="javascript:;" class="continue"></a></div>' +
		'</div>').children('a').click(function(e) {
				e.preventDefault();
				jQuery('#pochetteHover').toggle();
				if(BYMN.defaultVars.cache['pochetteAjax'] != true) {
					jQuery.ajax({
						url: mainUrl + 'mycart/index/getcart/',
						dataType: 'json',
						beforeSend: function() {
						  BYMN.defaultVars.cache['pochetteAjax'] = true;
						  jQuery('#pochetteHover').append('<div class="pochetteLoad" style="width: 100%; position: absolute; background-color: #000; z-index: 1000; height: 212px; left: 0; top: 25px; opacity: 0.7;"></div>' + 
						  '<img class="pochetteLoad" style="position: absolute; z-index: 1001; left: 134px; top: 90px;" src="'+ mainTemplateUrl +'images/ajax-loader.gif" />');
						},
						success: function(res) {
							jQuery('.pochetteLoad').remove();
							if(res.status == 1) {
								jQuery('#headerCart').empty();
								jQuery('#headerCart').append('<tr><td style="height: 136px; width: 309px;"><h3>'+res.message+'</h3><p>'+res.message2+'</p></td></tr>');
							} else {
								var pochetteItems = '';
								jQuery.each(res.data.items, function(i, cartItem) {
									pochetteItems +='    <tr>' +
													'      <td width="74"><img src="'+ cartItem.image +'" border="0" width="67" height="67" /></td>' +
													'      <td width="148"><strong>'+cartItem.product_name+'</strong><br />'+BYMN.format.TL(cartItem.row_total)+'</td>' +
													'      <td width="87">'+cartItem.qty+' ADET</td>' +
													'    </tr>';
								});
								jQuery('#headerCart').empty();
								jQuery('#headerCart').html(pochetteItems);
								jQuery('#itemCount').html(res.data.total.qty);
								jQuery('#totalPrice').html(BYMN.format.TL(res.data.total.amount));
							}
							BYMN.headerCartEvents();
							BYMN.defaultVars.cache['pochetteAjax'] = false;
						}
					});
				}
	});
}

BYMN.headerCartEvents = function() {
	BYMN.defaultVars.cache['#headercart'] = {
		current : 0,
		total : jQuery('#headerCart').children('tr').length
	};
	jQuery('#myPochette a.animateTop').unbind('click').click(function(e) {
		e.preventDefault();
		var cach = BYMN.defaultVars.cache['#headercart'];
		if(cach.current > 0) {
			var newTop = ((cach.current-1)*-68) + "px";
			if(!BYMN.defaultVars.isAnimate['#headercart']) {
				BYMN.defaultVars.isAnimate['#headercart'] = true;
				jQuery('#headerCart').animate({marginTop : [newTop, "linear"]}, 300, function(){
					BYMN.defaultVars.isAnimate['#headercart'] = false;
					BYMN.defaultVars.cache['#headercart'].current = cach.current - 1;
				});
			}
		}
	});
	
	jQuery('#myPochette a.animateDown').unbind('click').click(function(e) {
		e.preventDefault();
		var cach = BYMN.defaultVars.cache['#headercart'];
		if(cach.current < cach.total - 2) {
			var newTop = ((cach.current+1)*-68) + "px";
			if(!BYMN.defaultVars.isAnimate['#headercart']) {
				BYMN.defaultVars.isAnimate['#headercart'] = true;
				jQuery('#headerCart').animate({marginTop : [newTop, "swing"]}, 300, function(){
					BYMN.defaultVars.isAnimate['#headercart'] = false;
					BYMN.defaultVars.cache['#headercart'].current = cach.current + 1;
				});
			}
		}
	});
	
	jQuery('#decide a.close').unbind('click').click(function(e) {
		e.preventDefault();
		jQuery('#pochetteHover').toggle();
	});
	
	jQuery('#decide a.continue').unbind('click').click(function(e) {
		e.preventDefault();
		location.href = jQuery('#pochetteTopLink').attr('href');
	});
	
	
}

BYMN.format = {
	TL : function(amount) {
		amount = amount.toString().replace(/\$|\,/g,'');
		if(isNaN(amount))
			amount = "0";
		sign = (amount == (amount = Math.abs(amount)));
		amount = Math.floor(amount*100+0.50000000001);
		cents = amount%100;
		amount = Math.floor(amount/100).toString();
		if(cents<10)
			cents = "0" + cents;
		for (var i = 0; i < Math.floor((amount.length-(1+i))/3); i++)
			amount = amount.substring(0,amount.length-(4*i+3))+','+amount.substring(amount.length-(4*i+3));
		return (((sign)?'':'-') +  amount + '.' + cents + ' TL');
	}
}

BYMN.goNewsLetter = function() {
	var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
	var inputvalue = jQuery('#foInput input:first').val();
	if(pattern.test(inputvalue)){
		var itemData = jQuery('#foInput>form').serialize();
		jQuery.post(mainUrl + 'newsletter/subscriber/new', itemData,  function(data) {
			jQuery('#foSearch div').toggle();
		});
	}else{
			alert("Email adresi hatalı!");
	}
}

BYMN.footerEvents = function() {
	jQuery('#foInput input').bind({
		focusin : function(){
			if(jQuery(this).val() === "Email Adresiniz") {
				jQuery(this).val('');
			}
		},
		focusout : function(){
			if(jQuery.trim(jQuery(this).val()) === "") {
				jQuery(this).val('Email Adresiniz');
			}
		}
	});
	
	jQuery('#foClick a').click(function(){
		BYMN.goNewsLetter();	
	});
}

BYMN.fx = {
	accordion : {
		init : function(callback) {
			var func = callback || BYMN.defaultVars.nullFunc;
			var handlers = jQuery('.accordionClicker');
			var contents = jQuery('.hiddenContent');
			
			jQuery.each(handlers, function(i, handler) {
				jQuery(handler).click(function() {
                                        if(jQuery(contents[i]).hasClass('acik')) {
                                            jQuery(contents[i]).fadeOut(500).removeClass('acik');
                                        } else {
                                            jQuery('.hiddenContent').removeClass('acik')
                                            jQuery('.hiddenContent').hide();
                                            jQuery(contents[i]).fadeIn(500).addClass('acik');
                                        }
					func(this);
				});
			});
		}
	}
}

BYMN.specialFuncs = {
	sss : function(that) {
		jQuery(that).parent().siblings().removeClass('selected');
		jQuery(that).parent().addClass('selected');
	}
}

jQuery(document).ready(function() {
	BYMN.setTopMenu();
	//<![CDATA[
	//var dataForm = new VarienForm('header_login_form', true);
	//]]> 
    BYMN.createNavMenu();
	BYMN.animateNews.create();
	BYMN.fx.accordion.init(BYMN.specialFuncs.sss);
  
	BYMN.footerEvents();
	jQuery('.ajax-link').ajaxLink();
	
	//product page / image gallery
	jQuery('#productImage').imageGallery();

  jQuery('.tab-control').tabControl();
  
  //product page/recently viewed products slider
  jQuery('.horizontal-slider').horizontalSlider();
  
  jQuery('#newsletterform').submit(function() {
    BYMN.goNewsLetter();
    return false;
  });
    jQuery("#teslimat-iade").ajaxLink({
        notAjax   : true
    });
    
    jQuery("#productMeasurementTable").ajaxLink({
        notAjax   : true,
        noMargin : true
    });
   // ################beymen dunyasi slider#################3
    (function ($) {
    $('#newsButtons .prev').click(function (e) {
        e.preventDefault();
        $('#promoNewsContent ul').stop(true, true);
        var curTop = parseInt($('#promoNewsContent ul').css('margin-top'));
        var liLen = $('#promoNewsContent ul li');
        if (-1 * liLen.length * 84 != curTop - 84) $('#promoNewsContent ul').animate({
            marginTop: curTop - 84
        });
    });
    $('#newsButtons .next').click(function (e) {
        e.preventDefault();
        $('#promoNewsContent ul').stop(true, true);
        var curTop = parseInt($('#promoNewsContent ul').css('margin-top'));
        if (curTop <= -84) $('#promoNewsContent ul').animate({
            marginTop: curTop + 84
        });
    });
})(jQuery);
});

var isSuccess = false;
