jQuery.noConflict();
jQuery(function(){
	initGallery({
		holder:'.product-images-gallery',
		list:'div.main-image ul',
		switcher:'.thumbnails ul > li',
		autoRotation:false,
		prev:'a.btn-prev',
		next:'a.btn-next',
		effect:'fade'
	});
	if(typeof jQuery('a.view-link').lightBox != 'undefined') jQuery('a.view-link').lightBox();
	jQuery('ul.accordion').acc({
		speed: 400,
		active: 'selected',
		list: '.children()',
		opener: 'a.opener',
		slide: '.slide'
	});

});

//Window load
jQuery(window).load(function(){
	jQuery('#isotope').isotope({
		itemSelector : '.item',
		masonry : {
			columnWidth : 1
		},
		animationEngine: 'jquery',
		animationOptions: {
			duration: 750,
			easing: 'linear',
			queue: false
		},
		getSortData : {
			priority : function ( $elem ) {
				var output;
				if (($elem.attr('priority')) == undefined) {
					output = 100;
				} else {
					output = $elem.attr('priority');
				}
				return parseInt(output);
			}
		},
		sortBy : 'priority'
	});
});

jQuery.fn.acc = function(_options){
	var _options = jQuery.extend({
		speed: 400,
		active: 'active',
		list: '.children()',
		opener: 'a.opener',
		slide: 'div.slide'
	}, _options);
	return this.each(function(){
		var _list = eval('jQuery(this)' + _options.list);
		var _active = _options.active;
		var _speed = _options.speed;
		var _a = _list.index(_list.filter('.' + _active + ':eq(0)'));
		if(_a != -1) _list.removeClass(_active).eq(_a).addClass(_active);
		for(var i = 0; i < _list.length; i++){
			_list.eq(i).data('btn', _list.eq(i).children(_options.opener).eq(0));
			_list.eq(i).data('box', _list.eq(i).children(_options.slide).eq(0));
			if(i == _a) _list.eq(i).data('box').css('display', 'block');
			else _list.eq(i).data('box').css('display', 'none');
			_list.eq(i).data('btn').data('ind', i);
			_list.eq(i).data('btn').click(function(){
				if (_list.eq(jQuery(this).data('ind')).data('box').length != 0) {
					changeEl(jQuery(this).data('ind'));
					return false;
				}
			});
		}
		var anim_f = true;
		var a_h, ind_h, _k;
		function changeEl(_ind){
			if(anim_f){
				anim_f = false;
				if(_a == _ind){
					_list.eq(_a).removeClass(_active).data('box').animate({height: 0}, {
						duration: _speed,
						complete: function(){
							jQuery(this).css({display:'none', height:'auto'});
							_a = -1;
							anim_f = true;
						}
					});
				}
				else{
					_list.eq(_ind).data('box').css('display', 'block');
					ind_h = _list.eq(_ind).data('box').outerHeight();
					_list.eq(_ind).data('box').height(0);
					if(_a != -1){
						a_h = _list.eq(_a).removeClass(_active).data('box').outerHeight();
						_k = a_h/ind_h;
					}
					_list.eq(_ind).addClass(_active).data('box').animate({height: ind_h}, {
						duration: _speed,
						step: function(t_h){
							if(_a != -1) _list.eq(_a).data('box').height(a_h - t_h*_k);
						},
						complete: function(){
							_list.eq(_ind).data('box').height('auto');
							if(_a != -1) _list.eq(_a).data('box').css({display:'none', height: 'auto'});
							_a = _ind;
							anim_f = true;
						}
					});
				}
			}
		}
	});
}

function initGallery(option){
	var hold = jQuery(option.holder);
	var duration = option.autoRotation;
	var switcher = option.switcher || false;
	var event = option.event || 'click';
	hold.each(function(){
		var _this = jQuery(this);
		var list = _this.find(option.list),
			count = list.children().length,
			w = list.parent().width(),
			_t,
			a = 0,
			r = a;

		if(option.prev && option.next){
			var prev = _this.find(option.prev).attr('rel', 'prev').click(animateSlide);
			var next = _this.find(option.next).attr('rel', 'next').click(animateSlide);
		}
		if(option.switcher){
			switcher = _this.find(switcher);
			switcher.eq(r).removeClass('active');
			switcher.eq(a).addClass('active');
			switcher.bind(event, function(){
				var ind = switcher.index(jQuery(this));
				animateSlide(ind);
				return false;
			});
		}
		if(option.autoRotation) runTimer();
		if(option.effect == 'fade') {
			list.children().css('opacity', 0).removeClass('active');
			list.children().eq(a).css('opacity', 1).addClass('active');
		}
		if(option.stopOnHover && _t){
			list.mouseenter(function(){
				clearTimeout(_t);
			}).mouseleave(runTimer);
		}
		function runTimer(){
			_t = setTimeout(function(){
				animateSlide('next');
			}, duration);
		}
		
		function animateSlide(e){
			r = a;
			if(typeof e == 'string' && e == 'next') a++;
			else if(typeof e == 'number') a=e;
			else{
				if(e.target.rel == 'next') a++;
				else if(e.target.rel == 'prev') a--;
			}
			if(_t) clearTimeout(_t);
			if(a == count) a=0;
			else if(a == -1) a=count-1;
			list.children().eq(r).removeClass('active');
			list.children().eq(a).addClass('active');
			if(option.switcher){
				switcher.eq(r).removeClass('active');
				switcher.eq(a).addClass('active');
				
				var switchCount = switcher.parent().parent().height();
				var rc = Math.floor(switchCount/switcher.eq(0).outerHeight(true));
				var rcv = switcher.length;
				
				if( rcv > rc ) {
					var _slideEl=3;
					var _slide = 0;
					var _curSlideSet = Math.ceil( (a + 1) / _slideEl) ;
					_slide = _slideEl * (_curSlideSet - 1);
					if(_slide + _slideEl < rcv){
						_slide = _slide;
					}
					else {
						_slide = rcv - _slideEl;
					}
					switcher.parent().stop().animate({ marginTop: -_slide*switcher.eq(0).outerHeight(true) }, 500);
				}
			}
			if(option.effect == 'fade'){
				list.children().eq(r).animate({opacity:0}, {queue:false, duration:700});
				list.children().eq(a).animate({opacity:1}, {queue:false, duration:700, complete:function(){
					if(option.autoRotation) runTimer();
				}});
			}
			else{
				list.animate({marginLeft:-w*a}, {queue:false, duration:700, complete:function(){
					if(option.autoRotation) runTimer();
				}});
			}
			return false;
		}
	});
};

//Document ready
jQuery(document).ready(function() {
		try{
		jQuery('.bespoke_container #featured').orbit();		
		}
		catch(err){}
		// Trap the event when the user clicks on the sizechart link.
      //javascript to reslove edit cart popup issue when popup loads up with error
        if (self.parent && !(self.parent===self)){

            var parentbodyclass = jQuery.trim(window.parent.jQuery('body').attr('class'));
         
            if(parentbodyclass == "checkout-cart-index"){
                jQuery('body').addClass('checkout-cart-configure');
               
                
               
                if(document.location == "http://www.politix.com.au/checkout/cart/")
                {self.parent.location=document.location}
                
                
                
            }
        
        }
	//Append the InputFocus() and InputBlur() functions to any elements with the class "clearvalue"
	jQuery(".clearvalue").focus(function() { InputFocus(this); });
	jQuery(".clearvalue").blur(function() { InputBlur(this); });
	jQuery(".more-views li").first().addClass("firstli");
	jQuery(".more-views li").last().addClass("lastli");
	//fancybox - width and height for iframes only
        var outfit = false;
        if(jQuery("body").hasClass('outfitlayout')){
            outfit = true;

        }
	jQuery('.lightbox').fancybox({
            
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'		:	400, 
		'speedOut'		:	200,
		'autoScale'		:	false,
		'width'			:	500,
		'height'			:	600,
                'onStart':function() {
                                 if(outfit){
                                       jQuery("body").removeClass('outfitlayout');
                                         jQuery("body").removeClass('category-outfits');
                                         jQuery("#fancybox-content").show();
                                  }
                                   
                                },
                'onClosed'		: function() {
                                  if(outfit){
                                       jQuery("body").addClass('outfitlayout');
                                       jQuery("body").addClass('category-outfits');
                                  }
                                }
	});
	
	refresh_bag();	//add bag and cart JS, e.g. lightbox popups
	refresh_login();
	jQuery('.Outfits .product-image').click(function(){
		jQuery.fancybox.showActivity();
		var url = jQuery(this).attr("href") + "?popup=1";
		jQuery(".currentoutfit").removeClass("currentoutfit");
		jQuery(this).addClass("currentoutfit");
		var classname = jQuery(".currentoutfit").parent().attr('class');
		if(classname == "product-img-box")
		{
			jQuery(".more-views li").first().addClass("nextoutfit");
			jQuery(".more-views li").last().addClass("prevoutfit");
		}
		else if(classname == "firstli")
		{
			jQuery(this).parent().next().addClass("nextoutfit");
			jQuery(".product-img-box").addClass("prevoutfit");
		}
		else if(classname == "lastli")
		{
			jQuery(".product-img-box").addClass("nextoutfit");
			jQuery(this).parent().prev().addClass("prevoutfit");
		}
		else
		{
			jQuery(this).parent().next().addClass("nextoutfit");
			jQuery(this).parent().prev().addClass("prevoutfit");
		}
		jQuery.fancybox({
			'width'				: 825,
			'height'			: 820,
			'transitionIn'	:	'elastic',
			'transitionOut'	:	'elastic',
			'speedIn'		:	400, 
			'speedOut'		:	200,
			'autoScale'		:	false,
			'href' : url,
			'type' : 'iframe',
			'scrolling' : 'no',
			'onComplete' : function(){
				jQuery.fancybox.showActivity();
				jQuery("#fancybox-close").hide();
			},
			'onClosed' : function(){
				jQuery("#fancybox-content").hide();
				jQuery(".currentoutfit").removeClass("currentoutfit");
				jQuery(".nextoutfit").removeClass("nextoutfit");
				jQuery(".prevoutfit").removeClass("prevoutfit");
			}
			//

		});
		
		return false;
	
	});
	
	//show/hide politix bag when clicking the button
	jQuery('#header .top-link-cart').click(function() {
		jQuery('.politix-bag').slideToggle(1000);
		jQuery(this).toggleClass('active');
		if (jQuery('.politix-bag:visible').length > 0) {
			refresh_bag_scrollbar();	//refresh bag dropdown scrollbar if bag is showing
		}
		return false;
	});
	
	//hide the politix bag when clicking anywhere else, except on fancybox
	jQuery('body').click(function(event) {
		if (!jQuery(event.target).closest('.politix-bag, #fancybox-overlay, #fancybox-wrap').length) {
			jQuery('.politix-bag').hide();
			jQuery('#header .top-link-cart').removeClass('active');
		};
	});
	
	//bag empty message
	refresh_bag_empty_message();
	
	//init cart edit popup
	init_cart_edit_popup();
});

function ajax_remove_cart_item(element) {
	var delete_url =	jQuery(element).attr('href'); 
	var cart_item_id =	jQuery(element).attr('rel'); 
	jQuery(element).text('...');
	jQuery.ajax({
		dataType: 'html',
		url: delete_url,
		cache: false,
		success: function(data){
			var bag_has_items = true;
			jQuery('.notice-msg').hide();	//hide notice/success/error messages
			jQuery('.success-msg').hide();
			jQuery('.error-msg-msg').hide();
			jQuery(element).closest('.bag-item').fadeOut(function(){
				jQuery(this).remove(); //remove item from bag
				bag_has_items = refresh_bag_empty_message(); //check for bag empty
				refresh_bag_totals(data);	//refresh bag totals
			});
			jQuery('#cart_item_' + cart_item_id).fadeOut(function(){
				jQuery(this).remove();	//fade out the item from the main cart
				refresh_main_cart_view(bag_has_items);  //update the main cart area - only refresh the totals if bag has items
			});
		}
	});
}

function refresh_bag_empty_message() {
	if (jQuery('.politix-bag .bag-item').length == 0) {
		jQuery('.politix-bag .empty-message').show();
		return false;
	} else {
		jQuery('.politix-bag .empty-message').hide();
		return true;
	}
}

function refresh_bag_totals(data) {
	var bag_status_text = jQuery(data).find('.bag_status_text').html();
	var cart_items_qty = jQuery(data).find('.cart_items_qty').html();
	jQuery('#header .top-link-cart').html('My Politix Bag (' + cart_items_qty + ')');
	jQuery('.politix-bag .bag_status_text').html(bag_status_text);
}
function refresh_login(){
	jQuery.ajax({
		dataType: 'html',
		url: '/magento-login-update2.php',
		cache: false,
		success: function(data){
			
			jQuery(".links .first").html(data);
			
		}
	});
	
}
function refresh_bag() {		//refresh everything in the bag dropdown
	jQuery.ajax({
		dataType: 'html',
		url: '/ajax-cart.php',
		cache: false,
		success: function(data){
			var bag_html = jQuery('.bag_items_list', data).html();
			jQuery('.politix-bag .cart-view .inner').html(bag_html); //get the data from the ajax request to update the bag items list
			refresh_bag_and_cart_js();	//re-apply any JS to bag
			refresh_bag_totals(data);
		}
	});
}
function refresh_bag2() {		//refresh everything in the bag dropdown
	jQuery.ajax({
		dataType: 'html',
		url: '/ajax-cart.php',
		cache: false,
		success: function(data){
			var bag_html = jQuery('.bag_items_list', data).html();
			jQuery('.politix-bag .cart-view .inner').html(bag_html); //get the data from the ajax request to update the bag items list
			refresh_bag_and_cart_js();	//re-apply any JS to bag
			refresh_bag_totals(data);
                        jQuery(".top-link-cart").trigger('click');
			jQuery('.ajsubmit').hide();
		}
	});
}
function refresh_main_cart_view(totals_only) {
	if (jQuery('.checkout-cart-index').length > 0) {	//check existence of cart page first
		//show updating message
		if (totals_only != true) {
			jQuery('#content').html('<div class="page-title title-buttons"><h1 class="bag-update-message">Updating your Politix bag...</h1></div><div class="cartloader"><img src="http://www.politix.com.au/skin/frontend/pro/Politix/css/../images/lightbox-ico-loading.gif" /></div> ');
		}
		
		//refresh the whole cart area
		jQuery.ajax({
			dataType: 'html',
			url: '/checkout/cart/',		//could make this more efficient with a custom page
			cache: false,
			success: function(data){
				//refresh either just the totals, or the whole #content area
				if (totals_only == true) {
					var totals_html = jQuery('#shopping-cart-totals-table', data).html();
                                        //jQuery('#shopping-cart-totals-table').empty();
                                       // alert(totals_html);
					jQuery('#shopping-cart-totals-table').html(totals_html); //get the data from the ajax request and append it to the screen
                                       
				} else {
					var content_html = jQuery('#content', data).html();
					jQuery('#content').html(content_html); //get the data from the ajax request and append it to the screen
					refresh_bag_and_cart_js();	//re-apply any JS to cart
				}
				
				//refresh the sidebar since it has a cart number display
				var sidebar_html = jQuery('#sidebar', data).html();
				jQuery('#sidebar').html(sidebar_html); //get the data from the ajax request and append it to the screen
				
			}
		});
	}
}

function refresh_bag_and_cart_js() {
	//open an edit window for a product
       
	jQuery('.cartlightbox').fancybox({
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'		:	400, 
		'speedOut'		:	200,
		'autoScale'		:	true,
		'type' : 'iframe',
		'width' : 606,
		'height' : 349,
		'padding' : 0,
		'scrolling' : 'no',
                'onComplete' : function(){
                                jQuery.fancybox.showActivity();
                              
                               

                }
	});
	
	//remove item from cart via ajax
	jQuery('.bag-remove').unbind('click');
	jQuery('.bag-remove').click(function(event) {
		ajax_remove_cart_item(jQuery(this));
		return false;
	});
	
	//refresh bag dropdown scrollbar
	refresh_bag_scrollbar();
}

function refresh_bag_scrollbar() {		//refresh bag dropdown scrollbar
	jQuery('.politix-bag .cart-view').jScrollPane({
		showArrows: true
	});
}

function init_cart_edit_popup() {
	jQuery('.checkout-cart-configure .product-essential').prepend('<div class="edit-bag-header"><span class="edit-bag-title">Edit Product</span></div>');
	jQuery('.checkout-cart-configure .product-essential').append('<div class="edit-bag-footer"><a class="save" href="javascript:;" onclick="jQuery(\'.btn-cart\').trigger(\'click\');">Save Changes &amp; Return</a></div>');
	var image_src = jQuery('.checkout-cart-configure .product-img-box .thumbnails img:first').attr('src');
	if (image_src) {
		jQuery('.checkout-cart-configure .product-options:first').before('<img src="'+image_src+'" alt="" class="product-thumbnail" />');	//add image
	}
}

function OutfitNext()
{
	var loadurl = jQuery(".nextoutfit a").attr('href')+ "?popup=1";
	
	jQuery.fancybox.showActivity();
	jQuery("#fancybox-content").hide();
	jQuery("#fancybox-close").hide();
	jQuery('#fancybox-frame').attr('src',loadurl);
		
	jQuery(".currentoutfit").removeClass("currentoutfit");
	jQuery(".nextoutfit a").addClass("currentoutfit");
	jQuery(".nextoutfit").removeClass("nextoutfit");
	jQuery(".prevoutfit").removeClass("prevoutfit");
	var classname = jQuery(".currentoutfit").parent().attr('class');
	if(classname == "product-img-box")
	{
		jQuery(".more-views li").first().addClass("nextoutfit");
		jQuery(".more-views li").last().addClass("prevoutfit");
	}
	else if(classname == "firstli")
	{
		jQuery(".currentoutfit").parent().next().addClass("nextoutfit");
		jQuery(".product-img-box").addClass("prevoutfit");
	}
	else if(classname == "lastli")
	{
		jQuery(".product-img-box").addClass("nextoutfit");
		jQuery(".currentoutfit").parent().prev().addClass("prevoutfit");
	}
	else
	{
		jQuery(".currentoutfit").parent().next().addClass("nextoutfit");
		jQuery(".currentoutfit").parent().prev().addClass("prevoutfit");
	}
}
function OutfitPrevious()
{
	var loadurl = jQuery(".prevoutfit a").attr('href')+ "?popup=1";
	//alert(loadurl);
	jQuery.fancybox.showActivity();
	jQuery("#fancybox-content").hide();
	jQuery("#fancybox-close").hide();
	jQuery('#fancybox-frame').attr('src',loadurl);

	jQuery(".currentoutfit").removeClass("currentoutfit");
	jQuery(".prevoutfit a").addClass("currentoutfit");
	jQuery(".nextoutfit").removeClass("nextoutfit");
	jQuery(".prevoutfit").removeClass("prevoutfit");
	var classname = jQuery(".currentoutfit").parent().attr('class');
	if(classname == "product-img-box")
	{
		jQuery(".more-views li").first().addClass("nextoutfit");
		jQuery(".more-views li").last().addClass("prevoutfit");
	}
	else if(classname == "firstli")
	{
		jQuery(".currentoutfit").parent().next().addClass("nextoutfit");
		jQuery(".product-img-box").addClass("prevoutfit");
	}
	else if(classname == "lastli")
	{
		jQuery(".product-img-box").addClass("nextoutfit");
		jQuery(".currentoutfit").parent().prev().addClass("prevoutfit");
	}
	else
	{
		jQuery(".currentoutfit").parent().next().addClass("nextoutfit");
		jQuery(".currentoutfit").parent().prev().addClass("prevoutfit");
	}
}
function InputFocus(element) {
	if (element.value == element.defaultValue) {
		element.value = "";
		jQuery(element).addClass('filled');
	}
}
function InputBlur(element) {
	if (element.value == "") {
		jQuery(element).removeClass('filled');
		element.value = element.defaultValue;
	}
}
