
var timer_thumb_fade = 41;
var rotate_coef = 11;
var top_position_coef = 4;
var left_position_coef = 1;

var count_img = 0;
var current_category_id = 0;
var img_height = 0;//123
var img_width = 0;//93
var images_per_row = 10;

var pos_left = new Array();
var pos_top = new Array();
var loading_counter = 0;
var image_src = new Array();
var image_description = new Array();
var image_title = new Array();
var current_image_index = 0;
//used if you want to enter view of a certain image
var img_index = undefined;

var animation_top_objs = new Array();
var animation_left_objs = new Array();

var toggle = true;

function loadSubcategories(category_id,current_category,sub_category,imgindex)
{
	clearInterval(auto_image_change_interval);
	toggle = true;
	current_category_id = sub_category;
	img_index = imgindex;
	$("#loading_preview").show();
	$('#c_gallery').css('left', '112px');
	$('#c_gallery').css('height', '650px');//this height is calculated dynamicly when image height is known
	$("#collection_container").hide();
	if($('#g_'+current_category).html() !== null)
	{
		$('#g_'+current_category).fadeOut('slow' ,function(){
			$('#c_gallery').html('');
			req_url = 'index2.php?option=com_collections&task=load_categories&main_active='+category_id+'&sub_active='+sub_category;
			$.ajax({
			  url: req_url,
			  success: function(data) {
				data = eval( "(" + data + ")" );
				image_description = null;
				image_description = new Array();
				for(var i in data.desc_array){
					image_description.push(data.desc_array[i]);
				}
				image_title = null;
				image_title = new Array();
				for(var i in data.title_array){
					image_title.push(data.title_array[i]);
				}
				var html_data = String(data.html_content);
			    dataParts = html_data.split('---');
			    $('#collCatContainer').html(dataParts[0]);
			    setTimeout(function(){
					if(jQuery.client.os == 'Mac'){
						activeLink = jQuery('a.collLink activeCollections');
						links = jQuery('a.collLink');
						activeLink.each(function(item) { /*alert(jQuery(this));*/ jQuery(this).addClass("mac"); });
						links.each(function(item) { /*alert(jQuery(this));*/ jQuery(this).addClass("mac"); });
					}
				}, 200);
			    gallery = '<div onclick="animateToCorner();" style="position:absolute;padding-top:10px;padding-left:10px;height:100%" id="g_'+sub_category+'">'+dataParts[1]+'</div>';
			    $('#c_gallery').append(gallery);
				count_img = $('#c_gallery img').size();
				image_src=null;
				image_src = new Array();
				var total_imgs = count_img;
				$('#c_gallery img').each(function(index) {
					image_src.push($("#img_"+index).attr('src'));
					if(!$.browser.msie){
						objImg = new Image();
						objImg.src = $("#img_"+index).attr('src');
						objImg.onload = function() {
							loading_counter++;
							if(loading_counter == total_imgs){
								loading_counter = 0;
								//wait for elements to properly enter the stage and div, then start rotation
								setTimeout(function(){rotateGallery()}, 200);
							}
						};
						objImg.onerror = function() {
							total_imgs--;
							if(loading_counter == total_imgs){
								loading_counter = 0;
								//wait for elements to properly enter the stage and div, then start rotation
								setTimeout(function(){rotateGallery()}, 200);
							}
						};
					}
				});
				if($.browser.msie){
					setTimeout(function(){rotateGallery()}, 500);
				}
			  }});
		});
		return;
	}
	$('#c_gallery').html('');
	req_url = 'index2.php?option=com_collections&task=load_categories&main_active='+category_id+'&sub_active='+sub_category;
	$.ajax({
	  url: req_url,
	  success: function(data) {
		data = eval( "(" + data + ")" );
		//image_description = null;
		image_description = new Array();
		for(var i in data.desc_array){
			image_description.push(data.desc_array[i]);
		}
		image_title = null;
		image_title = new Array();
		for(var i in data.title_array){
			image_title.push(data.title_array[i]);
		}
		var html_data = String(data.html_content);
	    dataParts = html_data.split('---');
	    $('#collCatContainer').html(dataParts[0]);
	    setTimeout(function(){
			if(jQuery.client.os == 'Mac'){
				activeLink = jQuery('a.collLink activeCollections');
				links = jQuery('a.collLink');
				activeLink.each(function(item) { jQuery(this).addClass("mac"); });
				links.each(function(item) { jQuery(this).addClass("mac"); });
			}
		}, 200);
	    gallery = '<div onclick="animateToCorner();" style="position:absolute;padding-top:10px;padding-left:10px;height:100%" id="g_'+sub_category+'">'+dataParts[1]+'</div>';
	    $('#c_gallery').append(gallery);
		count_img = $('#c_gallery img').size();
		image_src=null;
		image_src = new Array();
		var total_imgs = count_img;
		$('#c_gallery img').each(function(index) {
			image_src.push($("#img_"+index).attr('src'));
			if(!$.browser.msie){
				objImg = new Image();
				objImg.src = $("#img_"+index).attr('src');
				objImg.onload = function() {
					loading_counter++;
					if(loading_counter == total_imgs){
						loading_counter = 0;
						//wait for elements to properly enter the stage and div, then start rotation
						setTimeout(function(){rotateGallery()}, 200);
					}
				};
				objImg.onerror = function() {
					total_imgs--;
					if(loading_counter == total_imgs){
						loading_counter = 0;
						//wait for elements to properly enter the stage and div, then start rotation
						setTimeout(function(){rotateGallery()}, 200);
					}
				};
			}
		});
		if($.browser.msie){
			setTimeout(function(){rotateGallery()}, 500);
		}
	  }});
}

function showGallery(i)
{
	if(i == count_img)
	{
		//when we end the recursive calls check if we have to animate to a certain image given by global param
		if(img_index != undefined){
			//wait 2 seconds for images to finish rotation and position, then start animation and getting product detail on
			setTimeout(function(){
				animateToCorner();
				imageClicked(document.getElementById("img_"+img_index));
			}, 8000);
			return;
		}
		return;
	}
	if(Math.floor(Math.random() * 11) == 2)
	{
		$("#img_"+i).removeClass("tableImage_first");
		$("#img_"+i).addClass("tableImage_second");
	}
	if($.browser.msie){
		document.getElementById("img_"+i).firstChild.style.marginLeft = 5+"px";
		document.getElementById("img_"+i).firstChild.style.marginTop = 5+"px";
		document.getElementById("img_"+i).style.width = (img_width+20)+"px";
		document.getElementById("img_"+i).style.height = (img_height +20)+"px";
	}
	setTimeout(function(){showImgStageOne(i)}, 50*Math.floor(Math.random() * timer_thumb_fade));
	showGallery(i+1);
}

function showImgStageOne(i)
{
	$("#img_"+i).removeClass("tableImage_first");
	$("#img_"+i).addClass("tableImage_second");
	setTimeout(function(){showImgStageTwo(i)}, 50*Math.floor(Math.random() * timer_thumb_fade));
}

function showImgStageTwo(i)
{
	$("#img_"+i).removeClass("tableImage_second");
	$("#img_"+i).addClass("tableImage_third");
	/*if(i==0) {
		setTimeout(function(){$(".tableImage_third").mouseover(imageMouseOver);}, 1000);
	}*/
}

function startRotate(obj, index)
{
	addStyle(index);
	//rotate obj image
	$(obj).rotate(Math.floor(Math.random() * rotate_coef)-5);
	//if we are on out last image, then all are done, start fading them in
	if(index == count_img-1)
	{
		$("#loading_preview").hide();
		setTimeout(function(){showGallery(0)}, 50);
	}
}

function rotateGallery()
{
	count_img = $('#c_gallery img').size();
	if(!$("#img_0"))
		return;
	img_width = $("#img_0").width();
	img_height = $("#img_0").height();
	var val = Math.ceil(count_img / images_per_row) * img_height + 50;
	$('#c_gallery').css('height', val + 'px');
	$('#imageNumber').css('top', 40 + val + 'px');
	$('#c_gallery img').each(function(index) {
		var img_obj = this;
		setTimeout(function(){startRotate(img_obj, index)}, 15*(index+1));
	});
}

function addStyle(i)
{
	pos_left[i] = (img_width + Math.floor(Math.random() * left_position_coef)) * (i - images_per_row*Math.floor(i / images_per_row));
	pos_top[i] = (img_height + Math.floor(Math.random() * top_position_coef)) * Math.floor(i / images_per_row);
	//position elements abit more down, if you rotate, because of overflow you wont see corners right
	pos_top[i] += 10;
	pos_left[i] += 10;
	$("#img_"+i).css("top", pos_top[i]);
	$("#img_"+i).css("left", pos_left[i]);
}

function imageClicked(obj)
{
	//if we don't have this and id it means we call event function without event, therefor we must give obj param
	$('#imageNumber').html('');
	if(typeof(this.id) != "undefined"){
		//else obj is this instance, if we got here from normal click event
		obj = this;
	}else{
		//we have no click event, so we don't care about toggle, just get the image detail on screen
		$("#loading_preview").hide();
		var pos = obj.id.search('_');
		if(pos == -1)
			return;
		var id = obj.id.substr(pos+1);
		$("#collection_img_number").html((parseInt(id)+1));
		current_image_index = parseInt(id);
		$("#collection_img_description").html(image_description[current_image_index]);
		$("#collection_img_title").html(image_title[current_image_index]);
		$("#collection_large_image").attr("src", image_src[current_image_index].replace("thumb_", "full_"));
		$('#collection_container').fadeIn(2000);
		return;
	}
	if(toggle == true){
		var pos = obj.id.search('_');
		if(pos == -1)
			return;
		var id = obj.id.substr(pos+1);
		$("#collection_img_number").html((parseInt(id)+1));
		current_image_index = parseInt(id);
		$("#collection_img_description").html(image_description[current_image_index]);
		$("#collection_img_title").html(image_title[current_image_index]);
		$("#collection_large_image").attr("src", image_src[current_image_index].replace("thumb_", "full_"));
		setTimeout(function(){$('#collection_container').fadeIn(2000);}, 2000);
		return;
	}
	$('#collection_container').fadeOut(1500);
}

function collectionPrev()
{
	if(toggle == false){
		current_image_index--;
		if(current_image_index < 0)
			current_image_index = count_img - 1;
		$('#collection_container').fadeOut(800, function() {
			$("#collection_img_number").html(current_image_index+1);
			$("#collection_img_description").html(image_description[current_image_index]);
			$("#collection_img_title").html(image_title[current_image_index]);
			$("#collection_large_image").attr("src", image_src[current_image_index].replace("thumb_", "full_"));
			$('#collection_container').fadeIn(800);
		});
	}
}

function collectionNext()
{
	if(toggle == false){
		current_image_index++;
		if(current_image_index > count_img -1)
			current_image_index = 0;
		$('#collection_container').fadeOut(800, function() {
			$("#collection_img_number").html(current_image_index+1);
			$("#collection_img_description").html(image_description[current_image_index]);
			$("#collection_img_title").html(image_title[current_image_index]);
			$("#collection_large_image").attr("src", image_src[current_image_index].replace("thumb_", "full_"));
			$('#collection_container').fadeIn(800);
		});
	}
}

function getRandomNumber(numLow,numHigh)
{
	var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
    var numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
	return numRand;
}

function animateToCorner()
{
	if(toggle == true)
	{
		//stop object animation and delete it from objects array
		for(var i=0; i<animation_left_objs.length; i++)
		{
			var t = animation_left_objs.pop();
			t.stop();
			delete t;
		}
		//stop object animation and delete it from objects array
		for(var i=0; i<animation_top_objs.length; i++)
		{
			var t = animation_top_objs.pop();
			t.stop();
			delete t;
		}
		for(var i=0; i<count_img; i++)
		{
			var top = getRandomNumber(0,40);
			var left = getRandomNumber(710,740);
			var timer = Math.random()*2+1;
			var start = $("#img_"+i).offset().left - $('#g_'+current_category_id).offset().left;
			t1 = new Tween(document.getElementById('img_'+i).style,'left',Tween.regularEaseInOut,start,left,timer,'px');
			t1.start();
			//register tween animation object
			animation_left_objs.push(t1);
			var start1 = $("#img_"+i).offset().top - $('#g_'+current_category_id).offset().top;
			t2 = new Tween(document.getElementById('img_'+i).style,'top',Tween.regularEaseInOut,start1,top,timer,'px');
			t2.start();
			//register tween animation object
			animation_top_objs.push(t2);
		}
		toggle =!toggle;
		return;
	}
	//stop object animation and delete it from objects array
	for(var i=0; i<animation_left_objs.length; i++)
	{
		var t = animation_left_objs.pop();
		t.stop();
		delete t;
	}
	//stop object animation and delete it from objects array
	for(var i=0; i<animation_top_objs.length; i++)
	{
		var t = animation_top_objs.pop();
		t.stop();
		delete t;
	}
	for(var i=0; i<count_img; i++)
	{
		var top = getRandomNumber(0,40);
		var left = getRandomNumber(710,740);
		var timer = Math.random()*2+1;
		t1 = new Tween(document.getElementById('img_'+i).style,'left',Tween.regularEaseInOut,left,pos_left[i],timer,'px');
		t1.start();
		//register tween animation object
		animation_left_objs.push(t1);
		t2 = new Tween(document.getElementById('img_'+i).style,'top',Tween.regularEaseInOut,top,pos_top[i],timer,'px');
		t2.start();
		//register tween animation object
		animation_top_objs.push(t2);
	}
	toggle =!toggle;
}

function imageMouseOver(nr)
{
	$('#imageNumber').show();
	if(!toggle) {
		$('#imageNumber').hide();
	}
	var target = nr.target;
	parentDiv = $(target).parent();
	idParts = parentDiv.attr('id').split('_');
	val = parseInt(idParts[1])+1;
	$('#imageNumber').html('<a>'+val+'</a>');
}
