imagePreloader = function(imgFile) {
	var image = new Image();
	image.src = imgFile;
}

$(document).ready(function() {	
	$("body.contact input.textfield").each(function() {
		setFocusInOut($(this));
	});
	initMediaPage();
	if ( $("ul.view_type #mosaic_view").length ) {
		changeViewType('mosaic_view');
	}
	self.setInterval("preloading()",100);

});	

$(window).resize(function() {
	reSizeFullView();
});

preloading = function() {
	var _top = 0 - parseInt($("#preloading span").css("top"));	
	_top += 40;
	if ( _top>=480 ) _top = 0;
	$("#preloading span").css("top","-"+_top+"px");
}

initMediaPage = function() {
	
	if ( $("body.media #page_navigation .page_number").length>0 ) {
		var page_count = $("body.media #page_navigation .page_number").length;
		var spacing = 10;
		var p_width = 10;
		$("body.media #page_navigation").css("width",(p_width+spacing)*page_count+"px");
		$("body.media #page_navigation .page_number").click(function(){
			var params = $(this).attr("href").substring(1);		
			var filename = $("#h_filename").val();
			changeMediaPage(params,filename);
			return false;
		});
	}
	if ( $("body.media span.current_type").length ) {
		$("span.current_type").click(function(){
			$("ul#category_list").show();
		});
	}
	if ( $("a[rel=album]").length )	{	
		$("a[rel=album]").fancybox({
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'titlePosition' 	: 'over',			
			//'autoDimensions'	: true,
			//'autoScale'		: false,
			'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
				return '';
			},
			'onClosed'			: function() { closeFancybox(); }
		});
	}
	if ( $("a[rel=iframe]").length ) {
		$("a[rel=iframe]").fancybox({
			'transitionIn'      : 'none',
			'transitionOut'     : 'none',
			'titlePosition'     : 'over',
			'margin'            : '0',
			'padding'           : '10',
			'scrolling'         : 'no',
			'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
				return '';
			},
			'onClosed'			: function() { closeFancybox(); }
		});
	}
	if ( $("a[rel=inline]").length ) {
		$("a[rel=inline]").fancybox({
			'transitionIn'      : 'none',
			'transitionOut'     : 'none',
			'titlePosition'     : 'over',
			'padding'			: '10',
			'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
				return '';
			},
			'onClosed'			: function() { closeFancybox(); }
		});
	}	
	
	$("ul.view_type li a").click(function() {
		if ( $(this).hasClass('active') ) return false;
		var view_type = $(this).attr('id');
		if ( view_type!='full_view') {
			$("ul.view_type li a").removeClass('active');
			$(this).addClass('active');
			$(".main #gallery_container").removeClass().addClass(view_type);
		}
		changeViewType(view_type);
	});	
	
}

closeFancybox = function() {}

/*********************************** CHANGE GALLERY VIEW TYPE **********************************/
var image_h_v = [];
var image_patterns = "";
var total_count = 0;
var random_order = "";
var rules = [];
//rules.push(array,total,h,v,height)
//rules.push(["6,6","2","2","0","3"]);
//rules.push(["6,6","2","0","2","3"]);
//rules.push(["6,6","2","1","1","3"]);

//rules.push(["6,4,2","3","3","0","3"]);
rules.push(["6,4,2","3","2","1","3"]);
//rules.push(["6,4,1,1","4","4","0","3"]);
rules.push(["6,4,1,1","4","3","1","3"]);
//rules.push(["6,2,4","3","3","0","3"]);
rules.push(["6,2,4","3","2","1","3"]);
//rules.push(["6,1,1,4","4","4","0","3"]);
rules.push(["6,1,1,4","4","3","1","3"]);
//rules.push(["6,3,3,2","4","1","3","3"]);
//rules.push(["6,3,3,2","4","2","2","3"]);
//rules.push(["6,3,1,1,2","5","3","2","3"]);
rules.push(["6,3,1,1,2","5","4","1","3"]);
//rules.push(["6,3,3,1,1","5","2","3","3"]);
//rules.push(["6,3,3,1,1","5","3","2","3"]);
//rules.push(["6,3,1,1,1,1","6","4","2","3"]);
rules.push(["6,3,1,1,1,1","6","5","1","3"]);
//rules.push(["6,2,2,2","4","4","0","3"]);
//rules.push(["6,2,2,2","4","3","1","3"]);
//rules.push(["6,2,2,1,1","5","5","0","3"]);
//rules.push(["6,2,2,1,1","5","4","1","3"]);
//rules.push(["6,2,1,1,2","5","5","0","3"]);
rules.push(["6,2,1,1,2","5","4","1","3"]);
//rules.push(["6,1,1,2,2","5","5","0","3"]);
rules.push(["6,1,1,2,2","5","4","1","3"]);
//rules.push(["6,2,1,1,1,1","6","6","0","3"]);
rules.push(["6,2,1,1,1,1","6","5","1","3"]);
//rules.push(["6,1,1,2,1,1","6","6","0","3"]);
rules.push(["6,1,1,2,1,1","6","5","1","3"]);
//rules.push(["6,1,1,1,1,2","6","6","0","3"]);
rules.push(["6,1,1,1,1,2","6","5","1","3"]);
//rules.push(["6,1,1,1,1,1,1","7","7","0","3"]);
//rules.push(["6,1,1,1,1,1,1","7","6","1","3"]);
rules.push(["5,3","2","1","1","2"]);
rules.push(["3,5","2","1","1","2"]);
rules.push(["5,1,1","3","3","0","2"]);
rules.push(["4,4","2","2","0","2"]);
rules.push(["4,3,3","3","1","2","2"]);
rules.push(["3,4,3","3","1","2","2"]);
rules.push(["3,3,4","3","1","2","2"]);
rules.push(["4,2,2","3","3","0","2"]);
rules.push(["4,2,1,1","4","4","0","2"]);
rules.push(["4,1,1,2","4","4","0","2"]);
rules.push(["4,1,1,1,1","5","5","0","2"]);
rules.push(["3,3,3,3","4","0","4","2"]);
rules.push(["3,3,3,1,1","5","2","3","2"]);
rules.push(["3,3,2,2","4","2","2","2"]);
rules.push(["3,3,2,1,1","5","3","2","2"]);
rules.push(["3,3,1,1,2","5","3","2","2"]);
rules.push(["3,3,1,1,1,1","6","4","2","2"]);
rules.push(["2,2","2","2","0","1"]);
rules.push(["2,1,1","3","3","0","1"]);
rules.push(["1,2,1","3","3","0","1"]);
rules.push(["2,1,1","3","3","0","1"]);
rules.push(["1,1,1,1","4","4","0","1"]);

changeViewType = function(view_type) {	
	var image_path = "";
	total_count = $("#gallery_container a").length;	
	if ( view_type=='full_view' ) {
		displayPhotoFullView();
	}
	if ( view_type=='list_view') {
		image_h_v = [];				
		image_patterns = "";		
		random_order = "";
		$("#gallery_container a img").unwrap();
		$("#gallery_container a").each(function() {
			var image_width = 161;
			var image_height = 108;	
			if ( $(this).hasClass('horizontal') ) 
				$(this).removeClass().addClass('horizontal');
			if ( $(this).hasClass('vertical') ) {
				image_width = 72;
				$(this).removeClass().addClass('vertical');			
			}
			image_path = $(this).find('img').attr('src').replace('images','thumbnails');
			$(this).find('img').css("margin-left","0");
			$(this).find('img').css("margin-top","0");
			$(this).find('img').attr('src',image_path);
			$(this).find('img').attr('width',image_width);
			$(this).find('img').attr('height',image_height);
		});
	}
	if ( view_type=='mosaic_view') {								
		var useHVPattern = false;
		if ( useHVPattern ) {
			$("#gallery_container a").each(function() {
				if ( $(this).hasClass('horizontal') )
					image_h_v.push("h");
				if ( $(this).hasClass('vertical') )
					image_h_v.push("v");
			});
			// set image pattern -> rules[array,total,h,v,height,pattern];
			var temp = "";
			for (var i=0;i<rules.length;i++ ) {
				temp = rules[i][0];
				temp = replaceAll(temp,"1","h");
				temp = replaceAll(temp,"2","h");
				temp = replaceAll(temp,"3","v");
				temp = replaceAll(temp,"4","h");
				temp = replaceAll(temp,"5","h");
				if ( temp.indexOf("6")>-1 )	{
					if (rules[i][3]>0) { // check vertical count
						for (var j=0;j<rules[i][3];j++ ) {
							temp = temp.replace("6","v");
						}
					}
					temp = replaceAll(temp,"6","h");
				}
				rules[i].push(temp);
			}
			selectPattern(image_h_v.join(","));
			image_patterns = image_patterns.split(",");
			var n = 0;
			var image_width = 0;
			var image_height = 0;
			$("#gallery_container a").each(function() {
				image_path = $(this).find('img').attr('src').replace('thumbnails','images');
				//$(this).find('img').attr('src',image_path);
				if ( n<image_patterns.length ) {
					$(this).addClass('style'+image_patterns[n]);
					image_width = $(this).css("width").replace("px","");
					image_height = $(this).css("height").replace("px","");
					//$(this).find('img').attr('width',image_width);
					//$(this).find('img').attr('height',image_height);
					n++;
				}
			});
		} else {
			generateRandomOrder();
			random_order = random_order.split(",");
			var n = 0;
			// image size when normal state.
			var v_width = 0;
			var v_height = 0;
			// image size when mouseover ( enlarge )
			var e_width = 0;
			var e_height = 0;
			// start position for crop
			var start_x = 0;
			var start_y = 0;
			$("#gallery_container a").each(function() {
				var imgObj = $(this).find('img');
				$(imgObj).wrap("<div class='image_wrapper'></div>");
				if ( n<random_order.length ) {
					$(this).addClass('style'+random_order[n]);
					n++;
				}
				image_path = $(imgObj).attr('src').replace('thumbnails','images');
				$(imgObj).attr('src',image_path);
				v_height = parseInt($(this).css("height"));
				v_width = parseInt($(this).css("width"));
				e_width = v_width + 50;
				if ( $(this).hasClass('vertical') ) {
					e_height = Math.floor(e_width * 1.5);
				} else {
					e_height = Math.floor(e_width * 0.67);
				}
				if ( e_height<= v_height ) {
					e_height = v_height + 50;
					if ( $(this).hasClass('vertical') ) {
						e_width = Math.floor(e_height * 0.67);
					} else {
						e_width = Math.floor(e_height * 1.5);
					}
				}
				$(imgObj).attr('width',e_width);
				$(imgObj).attr('height',e_height);
				start_x = Math.floor((e_width-v_width)/2);
				start_y = Math.floor((e_height-v_height)/2);
				$(imgObj).css("margin-left","-"+start_x+"px");
				$(imgObj).css("margin-top","-"+start_y+"px");
			});
			//initMediaPage();
		}
	}
}
selectRandomNumber = function(number) {
	return Math.round(Math.random()*100)%number;
}
selectPattern = function(patterns) {
	var result = [];
	for (var i=0;i<rules.length;i++ ) {
		if ( patterns.indexOf(rules[i][5])==0 ) {
			result.push(rules[i]);
		}
	}
	if ( result.length>0 ) {	
		random = selectRandomNumber(result.length);
		if ( image_patterns=="" )
			image_patterns = result[random][0];
		else
			image_patterns += ","+result[random][0];
		selectPattern(patterns.replace(result[random][5]+",",""));
	}
}
generateRandomOrder = function() {
	var count = total_count;
	var random = 0;
	var random_height = 0;
	while ( count>1 ) {
		random_height = selectRandomNumber(3)+1; // 1,2,3
		random = selectRandomNumber(rules.length);
		if ( rules[random][4]!=random_height ) continue;
		if ( random_order=="" )
			random_order = rules[random][0];
		else
			random_order += ","+rules[random][0];
		count -= rules[random][1];
	}
}
replaceAll = function(txt, replace, with_this) {
	return txt.replace(new RegExp(replace, 'g'),with_this);
}
/****************************************************************************************/

/********************************* CHANGE MEIDA TYPE ********************************/
changeMediaType = function(obj) {
	if ( $(obj).find("span#switch").length==0 ) return false;
	if ( $(obj).find("span#switch").hasClass("left") ) {
		selectRightItem();
	} else {
		selectLeftItem();
	}
}
selectLeftItem = function() {
	$("#switch").css("background-position", "0px -10px");
	$("#switch").animate( {backgroundPosition:'-9px -10px'}, 100, 
		function() {
			$("#switch").removeClass("right");
			$("#switch").addClass("left");
			$(".media_type #photos").addClass("active");
			$(".media_type #videos").removeClass("active");
			$(".media_category .current_type").html($(".media_type #photos").html());
			$("ul#media_list").removeClass("videos");
			$("ul#media_list").addClass("photos");
			updateMediaListByType('photo');
		}
	);
}
selectRightItem = function() {
	$("#switch").animate( {backgroundPosition:'0px -10px'}, 100, 
		function() {
			$("#switch").css("background-position", "0 -20px");
			$("#switch").removeClass("left");
			$("#switch").addClass("right");
			$(".media_type #videos").addClass("active");
			$(".media_type #photos").removeClass("active");
			$(".media_category .current_type").html($(".media_type #videos").html());
			$("ul#media_list").removeClass("photos");
			$("ul#media_list").addClass("videos");
			updateMediaListByType('video');
		}
	);
}
updateMediaListByType = function(type) {
	//$(".overlay").show();
	$.ajax({
		type: "GET",
		url: "media.php",
		data: "type="+type,
		success: function(data){			
			var media_list = $.trim($(data).find("#content .main").html());
			var media_categories = $.trim($(data).find("ul#category_list").html());
			$("#content .main").html(media_list);
			$("ul#category_list").html(media_categories);
			initMediaPage();
			//$(".overlay").hide();
		},
		error: function(data) {
			alert("error in ajax");
		}
	});
}
/****************************************************************************************/

/*********************************** CHANGE MEDIA PAGE **********************************/
changeMediaPage = function(params,filename) {
	$.ajax({
		type: "GET",
		url: filename,
		data: params,
		success: function(data){
			var media_list = $.trim($(data).find("#content .main").html());
			$("#content .main").html(media_list);
			initMediaPage();
			//$(".overlay").hide();
		},
		error: function(data) {
			alert("error in ajax");
		}
	});
}
/****************************************************************************************/

/************************************ PHOTO FULL VIEW ***********************************/
var full_view_pos = 1;
var isFullView = false;
var isSwapping = false;
var isPreloading = false;
closeFullView = function() {
	//$("#full_view_wrapper").hide();
	$("#preloading").hide();
	isSwapping = false;
	isPreloading = false;
	$("#full_view_wrapper").animate({'opacity':'hide'},300,function(){
		isFullView = false;
	});
}
reSizeFullView = function() {
	if ( isFullView ) {	
		$("#full_view_wrapper img").each(function(){
			var size = $(this).attr("rel");
			size = size.split('x');
			var r_width = size[0];
			var r_height = size[1];
			var w_width = $(window).width();
			var w_height = $(window).height();
			var e_width = 0;
			var e_height = 0;
			var start_x = 0;
			var start_y = 0;
			if ( w_width > e_width ) {
				e_width = w_width;
				e_height = Math.ceil(w_width/r_width*r_height);
			}
			if ( e_height < w_height ) {
				e_height = w_height;
				e_width = Math.ceil(w_height/r_height*r_width);
			}
			start_x = Math.floor((e_width-w_width)/2);
			start_y = Math.floor((e_height-w_height)/2);
			$(this).attr({'width':e_width,'height':e_height}).css({'margin-left':'-'+start_x+'px', 'margin-top':'-'+start_y+'px'});
		});
	}
}
displayPhotoFullView = function() {
	if ( total_count==0 ) return false;
	full_view_pos = 1;
	isFullView = true;
	var current_img_path = "";
	var current_img_size = "";
	var current_img_obj = null;
	current_img_path = $("#gallery_container a:first").attr('href');
	current_img_path = current_img_path.replace('thumbnails/','images/');
	current_img_size = $("#gallery_container a:first").attr('rev');
	current_img_size = current_img_size.split('x');
	current_img_obj = generateFullSizedImage(current_img_size[0],current_img_size[1],current_img_path);
	isPreloading = true;
	$("#preloading").show();
	$(current_img_obj).load(function(){
		isPreloading = false;
		$("#preloading").hide();
		$("#full_view_wrapper .current_pos").html(current_img_obj);
		$("#full_view_wrapper").show();
	});
	setMoveButtons(full_view_pos);
}
setMoveButtons = function(pos) {
	$("#full_view_wrapper .move_prev").hide();
	$("#full_view_wrapper .move_next").hide();
	if ( total_count > 1 ) {
		if ( pos>1 ) $("#full_view_wrapper .move_prev").show();
		if ( pos<total_count ) $("#full_view_wrapper .move_next").show();
	}
}
generateFullSizedImage = function(r_width, r_height, img_path) {
	var w_width = $(window).width();
	var w_height = $(window).height();
	var e_width = 0;
	var e_height = 0;
	var start_x = 0;
	var start_y = 0;
	if ( w_width > e_width ) {
		e_width = w_width;
		e_height = Math.ceil(w_width/r_width*r_height);
	}
	if ( e_height < w_height ) {
		e_height = w_height;
		e_width = Math.ceil(w_height/r_height*r_width);
	}
	start_x = Math.floor((e_width-w_width)/2);
	start_y = Math.floor((e_height-w_height)/2);
	return $('<img/>').attr({'width':e_width,'height':e_height,'src':img_path,'rel':r_width+'x'+r_height}).css({'margin-left':'-'+start_x+'px', 'margin-top':'-'+start_y+'px'});
}
changeFullSizedPhoto = function(type) { // type is 'next' or 'prev'
	if ( full_view_pos==1 && type=='prev' ) return false;
	if ( full_view_pos==total_count && type=='next' ) return false;
	if ( isPreloading ) return false;
	if ( isSwapping ) return false;
	var swapping_time = 500;
	var new_img_path = "";
	var new_img_size = "";
	var new_img_obj = null;
	if ( type=='next') full_view_pos++;
	if ( type=='prev') full_view_pos--;	
	var $old = $("#full_view_wrapper .current_pos");
	var $new = $("#full_view_wrapper .new_pos");
	var new_img_path = $("#gallery_container a:nth-child("+full_view_pos+")").attr('href');
	new_img_path = new_img_path.replace('thumbnails/','images/');
	var new_img_size = $("#gallery_container a:nth-child("+full_view_pos+")").attr('rev');
	new_img_size = new_img_size.split('x');
	var new_img_obj = generateFullSizedImage(new_img_size[0],new_img_size[1],new_img_path);
	$new.html(new_img_obj);
	isPreloading = true;
	$("#preloading").show();
	$new.find("img").load(function(){
		isPreloading = false;
		$("#preloading").hide();
		isSwapping = true;
		$old.animate({'opacity':'hide'},swapping_time)
		.add($new.animate({'opacity':'show'},swapping_time,function(){		
			$old.removeClass().addClass('new_pos');
			$new.removeClass().addClass('current_pos');
			setMoveButtons(full_view_pos);
			isSwapping = false;
		}));
	});		
}
$(window).keydown(function(e){
	if ( isFullView ) {
		//alert(e.which);
		switch(e.keyCode) { 
			case 27: // ESC
				closeFullView();
				break;			
			case 37: // <-
				changeFullSizedPhoto('prev');
				break;
			case 39: // ->
				changeFullSizedPhoto('next');
				break;
		}
	}
});
/*
$(window).bind('mousewheel', function(event, delta) {
	if ( isFullView ) {
		var dir = delta > 0 ? 'Up' : 'Down', vel = Math.abs(delta);
		//$(this).text(dir + ' at a velocity of ' + vel);
		if ( dir=='Up')
			changeFullSizedPhoto('prev');
		if ( dir=='Down' )
			changeFullSizedPhoto('next');
		return false;
	}
});
*/
/****************************************************************************************/

/*********************************** INDEX PAGE *****************************************/
$(window).load(function(){
	
	$("body.home #content img").animate({opacity:1},500);
		
	$('body.home #content img').each(function(){		
		var el = $(this);
		el.css({"position":"absolute"}).wrap("<div class='img_wrapper' style='display: inline-block'>").clone().addClass('img_grayscale').css({"position":"absolute","z-index":"998","opacity":"0"}).insertBefore(el).queue(function(){
			var el = $(this);
			el.parent().css({"width":this.width,"height":this.height});
			el.dequeue();
		});		
		this.src = grayscale(this.src);
	});	

	$('body.home #content img').mouseover(function(){
		$(this).parent().find('img:first').stop().animate({opacity:1}, 1000);
	})
	$('body.home #content img').mouseout(function(){
		$(this).stop().animate({opacity:0}, 1000);
	});			
});

grayscale = function(src) {
	var canvas = document.createElement('canvas');
	var ctx = canvas.getContext('2d');
	var imgObj = new Image();
	imgObj.src = src;
	canvas.width = imgObj.width;
	canvas.height = imgObj.height; 
	ctx.drawImage(imgObj, 0, 0); 
	var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
	for(var y = 0; y < imgPixels.height; y++){
		for(var x = 0; x < imgPixels.width; x++){
			var i = (y * 4) * imgPixels.width + x * 4;
			var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
			imgPixels.data[i] = avg; 
			imgPixels.data[i + 1] = avg; 
			imgPixels.data[i + 2] = avg;
		}
	}
	ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
	return canvas.toDataURL();
}
/****************************************************************************************/

/************************************ CONTACT PAGE **************************************/

setFocusInOut = function(obj) {
	var init_value = $(obj).val();
	var init_color = $(obj).css("color");
	var new_color = "#333333";
	$(obj).focus(function() {			
		if ( $(obj).val() == init_value ) {				
			$(obj).val("");
			$(obj).css("color", new_color);
		}
	});
	$(obj).focusout(function() {			
		if ( $(obj).val() == "" ) {				
			$(obj).val(init_value);
			$(obj).css("color", init_color);
		}
		if ( $(obj).val() == init_value ) {				
			$(obj).css("color", init_color);
		}
	});
}
submitContact = function() {
	$("form#contact input.textfield").removeClass("error");
	$("form#contact textarea").removeClass("error");
	var name = $.trim($("form#contact #txt_name").val());
	var name_init = "Name";
	var email = $.trim($("form#contact #txt_email").val());
	var email_init = "Email";
	var notes = $.trim($("form#contact #notes").val());
	if ( name=="" || name==name_init )	{
		$("form#contact #txt_name").addClass("error");
	}
	if ( email=="" || email==email_init || !validateEmail(email) ) {
		$("form#contact #txt_email").addClass("error");
	}
	if ( notes=="" ) {
		$("form#contact #notes").addClass("error");
	}
	if ($("form#contact .error").length>0 ) {
		return false;
	} else {
		$("form#contact #action_name").val("submit_contact");
		return true;
	}
}
validateEmail = function(email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	return reg.test(email);
}
/****************************************************************************************/
