var ajaxComplete = true;
var c = 0;
var t;
var timer_is_on = 0;
/** Subheader image rotator **/
var autoPlay = true;
var images = null;
var links = ['http://lenjerieerotica.ro', 'http://prov-pills.ro'];
var subheaderObj = null;
var subheaderImageObj = null;
var curentSubheaderImage = 1;
var nextSubheaderImage = curentSubheaderImage + 1;
var prevSubheaderImage = curentSubheaderImage - 1;
var totalSubheaderImages = 2;
var subheaderImageChange = false;
var navigationElementWidth = 18;
var navigationElementHeight = navigationElementWidth;
var navigationElementRightMargin = 5;
var navigationIndicatorInitialPosition = 4;
/** end **/

function map_init(){
    console.log('init');
}


function timeout(){
    return;
}

function initSubheader(){
    if(subheaderImageChange == true){
	   return;
    }
    subheaderImageChange = true;
    if(null == subheaderObj){
	   subheaderObj = jQuery('div#subheader');
	   subheaderImageObj = jQuery('#subheader #subheader_image');
    }
    if(subheaderObj.length < 1){
	   return;
    }

    if(null == images){
	   images = [];
	   var navigationElement = $('<div>');
	   navigationElement.attr('id', 'navigation');
	   for(i = 0; i < totalSubheaderImages; i++){
		  var img = new Image();
		  img.src = '/img/subheader_image_' + (i + 1) + '.jpg';
		  if(links[i] != null){
			 img = ('<a class="subheader_link" href="' + links[i] + '"><img src="' + img.src + '" /></a>');
		  //link.href = 'http://lenjerieerotica.ro/';
		  //link.append(img);
		  //			 img = link;
		  //img = link.html(img);
		  //console.log(img);
		  }
		  images.push(img);
		  var element = $('<span>');
		  element.attr('class', 'navigation_element');
		  element.attr('id', 'navigation_element-' + i);
		  element.css({
			 width: navigationElementWidth + 'px',
			 height: navigationElementHeight + 'px',
			 'margin-right': navigationElementRightMargin
		  });
		  element.appendTo(navigationElement);
	   }
	   navigationIndicator = $('<span>');
	   navigationIndicator.attr('id', 'navigationIndicator');
	   navigationIndicator.css({
		  left: navigationIndicatorInitialPosition
	   });
	   navigationIndicator.prependTo(navigationElement);
	   navigationElement.prependTo(subheaderImageObj);
    }
    setTimeout('subheaderImages(null)', 5000);
}

function subheaderImages(imageId){
    if(imageId != null){
	   curentSubheaderImage = imageId;
    }

    if(autoPlay == false){
	   if(imageId == null){
		  return;
	   }
    }
    var newImage = $(images[curentSubheaderImage]);

    $('.old_image').remove();
    var elementHeight = $(subheaderImageObj).height();
    var elementWidth = $(subheaderImageObj).width();
    console.log(elementWidth);
    newImage.css({
	   display:'inline',
	   'float': 'right',
	   height: elementHeight,
	   width: elementWidth
    });

    var curentImage = $('#curent_image');
    curentImage.css({
	   display: 'none'
    });


    curentImage.hide('slide', {
	   direction: 'left'
    }, 800, function(){
	   //jQuery('#subheader #subheader_image img').remove();
	   $(this).attr('class', 'old_image');
	   $(this).attr('id', '');
	   $(this).remove();
	   curentSubheaderImage = curentSubheaderImage + 1;

	   if(curentSubheaderImage == totalSubheaderImages){
		  curentSubheaderImage = 0;
		  nextSubheaderImage = 1;
		  prevSubheaderImage = totalSubheaderImages - 1;
	   }
	   else{

		  nextSubheaderImage = curentSubheaderImage + 1;
		  if(curentSubheaderImage == 0){
			 prevSubheaderImage = totalSubheaderImages;
		  }
		  else{
			 prevSubheaderImage = curentSubheaderImage - 1;
		  }
	   }
    });
    newImage.appendTo(subheaderImageObj);
    newImage.show('slide', {
	   direction: 'right'
    }, 800, function(){
	   $(this).removeClass('old_image');
	   $(this).attr('id', 'curent_image');
    });
    navigationIndicator.animate({
	   left: (navigationElementWidth * curentSubheaderImage) + (navigationElementRightMargin * curentSubheaderImage) + navigationIndicatorInitialPosition
    }, 800);

    subheaderImageChange = false;
    if(autoPlay == true){
	   setTimeout('subheaderImages(null)', 6200);
    }

}


function timedCount(){
    document.getElementById('txt').value=c;
    c=c+1;
    t=setTimeout("timedCount()",1000);
}

function doTimer(){
    if (!timer_is_on){
	   timer_is_on=1;
	   timedCount();
    }
}

function getRandProducts(){
    var container = jQuery('#products_wrapper.auto_refresh');
    jQuery.ajax({
	   url: '/home/randProducts.html',
	   type: 'post',
	   success: function(msg){
		  container.hide('slide', {
			 direction: 'left'
		  }, 500, function(){
			 container.html(msg);
		  });
		  container.show('slide', {
			 direction: 'right'
		  }, 300);
	   }
    });

    t = setTimeout('getRandProducts()', 10000);
}


function randProducts(){
    var productHolder = jQuery('#products_wrapper.auto_refresh');
    if(productHolder.length < 1){
	   return;
    }
    if (!timer_is_on){
	   timer_is_on=1;
	   getRandProducts();
    }
}

$(document).ready(function($){
    initSubheader();
    setTimeout('randProducts()', 10000);

    var shoppingBagX = $('#shopping_bag').offset().left;
    var shoppingBagY = $('#shopping_bag').offset().top;
    var shoppingBagH = $('#shopping_bag').css('height');
    var shoppingBagW = $('#shopping_bag').css('width');
    var speedConstant = 700; // 2.5 px/second


    $('span.navigation_element').live('click', function(){
	   $('.old_image').remove();
	   autoPlay = false;
	   if(subheaderImageChange){
		  subheaderImageChange = false;
		  return;
	   }
	   var imageId = $(this).attr('id').split('-').pop();
	   imageId = parseInt(imageId);

	   if(imageId == curentSubheaderImage){
	   //return;
	   }
	   subheaderImages(imageId);

    });
    $('#questions a').live('click', function(e){
	   e.preventDefault();
    });

    $( "#questions" ).accordion();

    $('a.remove_from_cart').live('click', function(e){
	   e.preventDefault();
	   var link = $(this).attr('href');
	   var _elm = $(this);
	   _elm.parents('tr').fadeOut(100, function(){
		  $.ajax({
			 url: link,
			 success: function(response){
				var message = $.parseJSON(response);
				if(message.success == true){
				    if(message.total_products == 0){
					   $('form#ComandaIndexForm').remove();
					   location.reload(false);
					   return;
				    }
				    $('#total span').html(message.total_cost);
				    $('#cart_num_products').html(message.total_products);
				    _elm.remove();
				}
				else{
				    _elm.fadeIn(100);
				}
			 }
		  });
	   });
    });
    var originalText = $('#normal_text').html();
    //    $('#adds_carousel').scrollable({
    //	   items: '#adds',
    //	   mousewheel: true,
    //	   circular: true
    //    }).autoscroll({
    //	   autoplay: true
    //    });

    $('#mapde area').click(function(e){
	   e.preventDefault();
	   //window.location.href = '#shop_map';
	   $.ajax({
		  url: $(this).attr('href'),
		  success: function(msg){
			 $('#normal_text').html(msg);
			 $('#shop_map').hide('blind', function(){
				$('#display_map').fadeIn();
				$('#normal_text').show('blind', function(){
				    $('.scrollable').scrollable({
					   circular: false,
					   mousewheel: true
				    });
				    $('.scrollable img:first').click();
				});

			 });

		  //$('.scrollable').filter(".scrollable img:first").console.log('.scrollable img:first').click();
		  //console.log($('.scrollable'));
		  /*$('#normal_text').fadeOut(150, function(){

				$(this).fadeIn(150);
				});*/
		  }
	   });

    });

    $('#display_map').click(function(){
	   $('#display_map').fadeOut();
	   $('#normal_text').hide('blind', function(){
		  $(this).html('');
		  $('#shop_map').show('blind');

	   });
    });
    /*	$(".scrollable").live('scrollable', function(){
	$(this).scrollable();
	});*/

    $(".items img").live('click', function() {

	   // see if same thumb is being clicked
	   if ($(this).hasClass("active")) {
		  return;
	   }

	   // calclulate large image's URL based on the thumbnail URL (flickr specific)
	   var url = $(this).attr("src").replace("_t", "");

	   // get handle to element that wraps the image and make it semi-transparent
	   var wrap = $("#image_wrap");

	   // the large image from www.flickr.com
	   var img = new Image();


	   // call this function after it's loaded
	   img.onload = function(){
		  wrap.fadeTo(150, 0.5, function(){
			 wrap.find('img').attr('src', url);

			 wrap.fadeTo(250, 1);
		  });

	   // make wrapper fully visible
	   /*wrap.fadeTo('fast', 1, function(){
			$(this).find("img").attr("src", url);
			});*/
	   // change the image
	   //img.src = url;
	   //wrap.

	   };

	   img.src = url;
	   $(".items img").removeClass("active");
	   $(this).addClass("active");
    });

    /*	$('#shop_info #shop_map area').cluetip({
	insertionElement: 'shop_info',
	attribute: 'href',
	positionBy: 'auto',
	topOffset: 15,
	leftOffset: 15,
	//mouseOutClose: true,
	activation: true,
	cursor: 'pointer',
	fx: {
	open: 'fadeIn',
	openSpeed: 200
	}
	});*/
    /*	$('#shop_map area').hover(function(){
	$(this).cluetip({
	attribute: 'href'
	});
	}, function(){
	//console.log('mouse out');
	});*/
    $('div.img img.overlay_trigger').overlay({
	   mask: '#000'
    });

    $('div[id^=overlay]').click(function(){
	   $(this).overlay('close');
    });
    $('span.shopping_cart a, span.buy_button a').live('click', function(e){
	   e.preventDefault();
	   //if(!ajaxComplete){
	   //	return;
	   //}
	   ajaxComplete = false;

	   var product_id = $(this).attr('id').split('_')[1];
	   var image = $('#img_' + product_id);
	   var imageH = image.css('height');
	   var imageW = image.css('width');
	   var imagePositionX = image.offset().left;
	   var imagePositionY = image.offset().top;
	   var distanceY = (imagePositionY - shoppingBagY);
	   var animationSpeed = (distanceY * speedConstant) / 300;

	   var transferContainer = $('<img />');
	   transferContainer.addClass('transfer');
	   transferContainer.attr('src', image.attr('src'));

	   transferContainer.css({
		  'height': imageH,
		  'width': imageW,
		  'position': 'absolute',
		  'z-index': '10000',
		  'top': imagePositionY + 'px',
		  'left': imagePositionX + 'px',
		  'opacity': '1'
	   });
	   $('body').append(transferContainer);
	   transferContainer.animate({
		  'top':shoppingBagY,
		  'left' : shoppingBagX,
		  'width': shoppingBagW,
		  'height' : shoppingBagH,
		  'opacity' : 0.5
	   }, animationSpeed, 'easeOutBack', function(){
		  $.ajax({
			 type: 'post',
			 url: '/cart/add/' + product_id,
			 success: function(msg){
				var message = $.parseJSON(msg);
				if(message.success == true){
				    $('#cart_num_products').html(message.total);

				}
			 },
			 complete: function(){
				ajaxComplete = true;
				transferContainer.animate({
				    'opacity': 0
				}, 200, function(){
				    transferContainer.remove();
				});
			 }
		  })
	   });
    //transferContainer.show();
    });

});

