/**
*
* Poster Class Function
*
*/

var base_url = "http://poster.us.com";
var current_url = window.location.href.replace(base_url , '');
var ajaxurl = 'http://poster.us.com/wp-admin/admin-ajax.php';


function poster()
{
	// all execution functions run here
	classFunction = this;
	
	
	this.tabs(); // change tabs
	this.scroll("span.left-arrow", "span.right-arrow", "ul.scroll-tab div.grid"); // main page gallery to scroll

	// single pages gallery
	this.scroll("span.left-arrow-1", "span.right-arrow-1", "ul.scroll-tab-1 div.grid");
	this.scroll2("span.left-arrow-2", "span.right-arrow-2", "ul.scroll-tab-2 div.grid");

	this.scrollTo(); // plugin to scroll to the top
	this.slider(); // slider on the main page
	this.getTablePosition();
	this.setGridClear(); // set fix for grid-clear css class
	
	
	// scale the images
	setTimeout(function() { 
	
		classFunction.scale('div.scaleItem');
	},500);
	
	
	// * addition
	this.improvments();

	
};

// scroll function [prototype]
poster.prototype.scroll = function(leftArrow, rightArrow, listBlock)
{
	currentPosition = 0;
	
	$(leftArrow).live("click", function() {	
		arrow = $(leftArrow);
		block = $(listBlock);
		size = block.size();
		width = block.width();
		currentPosition--;
		block.eq(currentPosition).show(200);

		arrow.show(); $(rightArrow).show();
		if(currentPosition == 0) { $(leftArrow).hide(); return false; }

	});

	$(rightArrow).live("click", function() {
		arrow = $(rightArrow);
		block = $(listBlock);
		size = block.size();
		width = block.width();
		block.eq(currentPosition).hide(200);
		currentPosition++;

		arrow.show(); $(leftArrow).show();
		if(currentPosition == (size - 1)) { arrow.hide(); return false; }
	});

};

// scroll function [prototype]
poster.prototype.scroll2 = function(leftArrow, rightArrow, listBlock)
{
	currentPosition2 = 0;
	
	$(leftArrow).live("click", function() {	
		arrow2 = $(leftArrow);
		block2 = $(listBlock);
		size2 = block2.size();
		width2 = block2.width();
		currentPosition2--;
		block2.eq(currentPosition2).show(200);

		arrow2.show(); $(rightArrow).show();
		if(currentPosition2 == 0) { $(leftArrow).hide(); return false; }

	});

	$(rightArrow).live("click", function() {
		arrow2 = $(rightArrow);
		block2 = $(listBlock);
		size2 = block2.size();
		width2 = block2.width();
		block2.eq(currentPosition2).hide(200);
		currentPosition2++;

		arrow2.show(); $(leftArrow).show();
		if(currentPosition2 == (size - 1)) { arrow2.hide(); return false; }
	});

};
/* ********************************************************** */
// tabs function [prototype]
poster.prototype.tabs = function()
{
	$("div#gallery ul.tabs").tabs("div.panes > div", {
		effect: 'ajax',
		onBeforeClick: function(event, i) { 
		    var pane = this.getPanes("div.panes > div"); 
			pane.html('<img src="'+base_url+'/wp-content/themes/posters/images/ajax-loader.gif" />');
			pane.load(this.getTabs().eq(i).attr("href"), function() {
				panelLoadSize = $('ul.scroll-tab div.grid').size();
				if(panelLoadSize == 1)
				{
					$('span.right-arrow').hide();
				}
			});  
			classFunction.getReset();
		}
	});
};
/* ********************************************************** */
// slider function [prototype]
poster.prototype.slider = function()
{
	$('#slider-images').aviaSlider({blockSize: {height: 80, width:80},transition: 'random',display: 'diagonaltop', animationSpeed : 1000});
	setInterval(function() { $('.active_item').siblings().css({'padding':'0'}); $('.active_item').css({paddingLeft : "4.5px", paddingRight : "4.5px"}); }, 1000);
};
/* ********************************************************** */
// scrollTo function [prototype]
poster.prototype.scrollTo = function()
{
$('a.back-top').click(function(e) {	e.preventDefault();	$.scrollTo($(this).attr('href'), 300); });
};
/* ********************************************************** */
// get table position for products [prototype]
poster.prototype.getTablePosition = function()
{

};
/* ********************************************************** */	
// reset function [prototype]
poster.prototype.getReset = function()
{
	return currentPosition = 0;	
};
/* ********************************************************** */
poster.prototype.setGridClear = function()
{
	var addClear = "<div class='clear'></div>";
	$('.grid-clear').append(addClear);
};


poster.prototype.improvments = function() {
	
	// @single.php
	/*
	if ($('#size').length > 0) {
		
		$('#size').bind('change', function() {
			$('#product-price').html( "$" + $('#size').find(':selected').attr('data-price')  );
			$('#product-data').attr('data-size-id', $('#size').find(':selected').val() ); // update size_id
		});
	}
	
	*/
	
	// persistent form checks
	$('.required').bind('blur', function() {
		if ($(this).val() == "") {
			$(this).css('border','1px solid #cc0000');
			$('#submit-button').attr('disabled', true);
			
		} else {
			$(this).css('border','1px solid #9C9C9C');
			$('#submit-button').removeAttr('disabled');
		}
	});
	

		
	
	
}

poster.prototype.scale = function(elem, scale, speed)
{

	/* some fix */

	$('div.scaleItem').each(function() {
		sizeW = $(this).find('img').width();
		
		$(this).css({
			'left' : (178 - sizeW) / 2 + "px",
			'top' : '15px'
		});
	});
	
	/* place the shadow ->>>>>>>>>>>>>> */
	$('span.shadow').each(function() {
		var sizeH = $(this).prev().height();
		var newSize = (sizeW - 115) / 2;
		$(this).css({
			'left' : (178 - sizeW) / 2 + newSize + "px",
			'top' : sizeH + 14.5 + "px"
		});
	});
	
	/* some fix */



	if(typeof scale == "undefined") { scale = 2; }
	if(typeof speed == "undefined") { speed = 300; }
	
	var block = $(elem);
	
	block.each(function(i) {
		
		var bwidth = $(this).width();
		var bheight = $(this).height();
		var iwidth = $(this).children('img')[0].clientWidth;
		var iheight = $(this).children('img')[0].clientHeight;
		
		var outputX = bwidth - iwidth;
		var	outputY = bheight - iheight;
		
		
 		
		var vbox = $(this).position(); /* get current top and left */
		
	
		$(this).hover(function() {

			$(this).stop(true).animate({
			'width' : bwidth * scale + "px",
			'height' : bheight * scale + "px",
			'top' : vbox.top - (iheight / 2),
			'left' : vbox.left - (iwidth / 2)
			}, speed);
			$(this).find('img').stop(true).animate({
				'width' : bwidth * scale - outputX + "px",
				'height' : bheight * scale - outputY + "px",
				'maxWidth' : '1000px',
				'maxHeight' : '1000px'
			}, speed);
		}, function() {
			$(this).stop(true).animate({
			'width' : bwidth + 'px',
			'height' : bheight + 'px',
			'top' : vbox.top,
			'left' : vbox.left
			}, speed);
			$(this).find('img').stop(true).animate({
				'width' : iwidth + 'px',
				'height' : iheight + 'px'
			}, speed);
		});
		
		
	});
	
}

jQuery(document).ready(function() {
	// init the class
	var p = new poster();	
	
	
}); // End


function showSuccess(text,delay)
{
	if (text != "" || text != undefined) { 
		$('.main-message .a-center span').text(text);
	}
	
	
	if (delay == undefined || delay == ""){var delay = 6000; }
	
	$('.main-message').stop().slideDown().delay(delay).slideUp();
		
	$('#remove-main-message').bind('click' , function() {
			$('.main-message').stop().slideUp();
	});
		
}


function showError(text,delay)
{
	if (text != "" || text != undefined) { 
		$('.main-error .a-center span').text(text);
	}
	
	
	if (delay == undefined || delay == ""){var delay = 6000; }
	
	$('.main-error').stop().slideDown().delay(delay).slideUp();
		
	$('#remove-error-message').bind('click' , function() {
			$('.main-error').stop().slideUp();
	});

}






jQuery(function() {
	
	
	// Section single.php
	
	// @add to cart
	if ($('.single-table').length > 0) {
		
		$('#add-to-cart').bind('click', function() {
			var self = $(this);
			self.html('Saving ...');
			var size_id = $('#product-data').attr('data-size-id');
			
			$.getJSON(ajaxurl, {action:'extern', 'do':'add-to-cart', size_id:size_id} , function(e) {
				if(e.err == false)
				{
					showSuccess(e.msg);
					self.html('Added to cart!');
					self.unbind();
				} else if (e.state == "exists")
				{
					showSuccess(e.msg);
					self.html('Added to cart !');
					self.unbind();
				} else
				{
					showError(e.err);
				}
			});
			
		});
		
		// @add to gallery
		$('#add-to-gallery').bind('click', function() {
			var self = $(this);
			self.html("Saving ...");
			var size_id = $('#product-data').attr('data-size-id');
			
				
				$.getJSON(ajaxurl, {action:'extern','do':'save-to-gallery',size_id:size_id} , function(e) {
						if(e.err == false)
						{
							showSuccess(e.msg);
							self.html('Saved in gallery!');
							self.unbind();
						} else if (e.state == "exists")
						{
							showError(e.err);
							self.html('Saved in gallery !');
							self.unbind();
						} else
						{
							showError(e.err);
						}
				}); 
		});
	
		
		$('input.single-table').bind('change focus click select keypress keyup' ,function(e) {e.preventDefault(); });
		$('.single-table').bind('click', function() {
			$('.prod-table').show(0);
		});
		
		$('body').click(function(event) {
			if (!$(event.target).closest('.single-table, table.prod-table').length) {
			   $('table.prod-table').hide();
			};
		});
		
		
		$('.prod-table tr').live('click',function(e){
			var size = $(this).children('td:first').html();
			var price = $(this).children('td:last').html();
			$('input.single-table').val( size );
			$('#product-price').html( price );
			$('#product-data').attr('data-size-id', $(this).attr('data-size-id') );
			$('.prod-table').hide(0);
		});
		
	}
	
	//section taxonomy-subjects.php
	// Add to cart or Add to Gallery
	$("div.grid-clear a.add-cart, div.grid-clear a.save-gallery").live('click', function(e) {
		e.preventDefault();
		var coor = $(this).position();
		
		$("table.prod-table").hide(0);
		
		var action = $(this).attr('class');
		var table = $(this).parent().children('table');
		
		var tableHeight = table.height() + 2;
		var tableWidth = table.width();
	
		table.css({
			display : "block",
			top : coor.top - tableHeight + "px",
			left : coor.left - tableWidth + (tableWidth / 2) + "px"
		});
		
		table.attr('data-action', action);
		
	});
	
    
	if (current_url.match(/subjects/gi) || window.location.search.match(/\?s\=/)) {
		
		// Hide list when clicked on body
		$('body').click(function(event) {
			if (!$(event.target).closest('a.add-cart,a.save-gallery, table.prod-table').length) {
			   $('table.prod-table').hide();
			};
		});
	
	
		// Add to cart or gallery
		$('table.prod-table tr').live('click', function() {
			var action = ($(this).parent().parent().attr('data-action') == "save-gallery") ? "save-to-gallery" : "add-to-cart";
			var size_id = $(this).attr('data-size-id');
			// send
			$.getJSON(ajaxurl, {action:'extern', 'do':action, size_id:size_id }, function(e) {
				if (action == "save-to-gallery")
				{
					if (e.err == false)
					{
						showSuccess(e.msg);
					} 
					else if (e.state == "exists")
					{
						showError(e.err);
					}
					else
					{
						showError(e.err);
					}
				} else 
				{
					if (e.err == false)
					{
						showSuccess(e.msg);
					}
					else if (e.state == "exists")
					{
						showSuccess(e.msg);
					}
					else
					{
						showError(e.err);
					}
				}
			});
		});
		
		
		
		$('#show-more').bind('click', function() {
			var self = $(this);
			var next = parseInt($(this).attr('data-current')) + 1;
			var category = $(this).attr('data-category');
			var sort_by = $(this).attr('data-sort-by');

			self.text('Loading ...');
			$.getJSON(ajaxurl, {action:'extern','do':'getNextPage',next:next,category:category,sort:sort_by}, function(e) {
				self.text('Show More');
				if (e.err == false)
				{
					$.each(e.response, function(key,val) {
						$('#show-more').before( val );
					});
					
					if (e.maxnum == next)
					{
						$('#show-more').unbind();
						$('#show-more').hide();
					} else
					{
						self.attr('data-current', next);
					}
					
					var posterClass = new poster();

				} 
				else
				{
					showError(e.err);
				}
			});
			return false;
		});
		
		
		
		$('#products-sort').bind('change', function() {
			$('#products-sort-form').submit();
		});
	
	} // tax subjects
	
	if (current_url.match(/my\-gallery/gi)) {
		
		//delete form gallery
		
		$('.delete-from-gallery').bind('click', function() {
			var self = $(this);
			self.val('Deleting ...');
			self.unbind();
			var prod = $(this).closest('.prod-style');
			
			
		    $.getJSON(ajaxurl,{action:'extern','do':'delete-from-gallery', 'size_id':$(this).attr('data-size-id')}, function(e){
				if (e.err == false)
				{
					prod.fadeOut();
					self.val('Deleted');
				}
				else
				{
					showError(e.err);
				}
			}); 
		});
	}
	
	if (current_url.match(/cart/gi)) {
	
	
	// delete from cart
	$('.remove-cart-item').bind('click', function(e) {
		var cart_item_id = $(this).attr('data-cart-item-id');
		$.getJSON(ajaxurl,{action:'extern','do':'delete-cart-item', cart_item_id : cart_item_id}, function(e){
			if (e.err == false)
			{
				$('#item-' + cart_item_id).fadeOut(100, function() {
						$(this).remove();
						reCountCart();
				});
				
			}
			else
			{
				showError(e.err);
			}
		});
		
		reCountCart();
		return false;
	});
	
	// update cart
	
	$('.update-qty').bind('click', function() {
		var cart_item_id = $(this).attr('data-cart-item-id');
		var qty = $(this).prev();
		var self = $(this);
		
		if (parseInt(qty.val()) >= 1) {
			
			qty.attr('disabled','true');
			
			self.html('Saving ...');
			
				$.getJSON(ajaxurl,{action:'extern','do':'update-cart-item', cart_item_id : cart_item_id, qty:qty.val()}, function(e){
					if (e.err == false)
					{
						showSuccess(e.msg);
						qty.removeAttr('disabled',true);
						self.html('update');
						reCalcPrices();
					}
					else
					{
						showError(e.err);
					}
				}); 
				return false;
		} else
		{
			showError('Quantity can not be less than 1 !');
			qty.val('').focus();
		}
	});
	
	
	
	}
	
	
	
	function reCountCart()
	{
		var items = parseInt( $('#shopping-table tr[id*=item]').length );
		$('#count-cart').html(items);
		reCalcPrices();
	}
	
	function reCalcPrices()
	{
		var items = $('#shopping-table tr[id*=item]');
		var total = $('#shopping-table tr.cart-caption').children('td:eq(3)');
		total.html(0);
		var maxShipping = parseFloat( $('#max-shipping').html() );
		items.each(function(){
		
			var price = parseFloat( $(this).children('td:eq(1)').html().replace(/[^\d|\.]/gi,'') );
			
			
			var qty = parseInt( $(this).children('td:eq(3)').children('input').val().replace(/[^\d]/gi,'') );
			var all = price * qty;
			
			$(this).children('td:eq(4)').html( "$ " +  all );
			
			total.html ( parseFloat(total.html())  + parseFloat( all)  );
			
		});
		
		var fullTotal = parseFloat(total.html()) + parseFloat(maxShipping);
		total.html ("$ " + fullTotal.toFixed(2) );
	}
	
	reCalcPrices();
	
	
	
	// improvements
	
	
	
	$('.jqzoom').jqzoom({
        zoomType: 'standard',
        lens:true,
        preloadImages: false,
        alwaysOn:false
    });
	
	    
	
	
});

