/**
 * common javascript functions
 *
 * @author Ethan Liu
 * @version $Id: functions.js 141 2009-09-02 13:35:36Z ethan $
 * @copyright Creativecrap.com, Ethan, 26 October, 2008
 * @package default
 **/

var l10n;
var timerNav;
$(function() {
	//swfobject.switchOffAutoHideShow();
	//$.ui.dialog.defaults.bgiframe = true;
	$("#asideloginform").uniform({callback: function(result, status) {
		if (result.success) {
			setTimeout(function() {
				if (result.cmd == 'redirect') {
					window.location.href = result.data;
				}
				else {
					window.location.reload();
				}
			}, 800);
		}
	}});
	
	$("#comment-form").uniform({
		//prepend: function() {},
		callback: function(result, status) {
			if (result.success) {
				var message = $("#comment-form textarea").val();
				$(".total_comments").text(parseInt($(".total_comments:first").text())+1);
				if ($("#facebookcomment").attr('checked')) {
					facebook_feed.message = message;
					FB.ui(facebook_feed);
				};
				//window.location = '#comments';
				$("#comment-form textarea").val('');
				$("#comment-form #submit").removeClass('disable');
				getComments();
			}
		}
	});
	
	/*
	$(".post-list-block .date").each(function(i, item) {
		var r = Math.floor(Math.random()*2+1);
		var op = (r==1) ? 1 : -1;
		var r = Math.floor(Math.random()*15+0) * op;
		$(item).css('-moz-transform', 'rotate('+r+'deg)');
		$(item).css('-webkit-transform', 'rotate('+r+'deg)');
		$(item).css('-o-transform', 'rotate('+r+'deg)');
	});
	*/
	
	// z-index fixed
	$("#navigation li, #navigation li a, .tags-cloud li, .tags-cloud li a").hover(function() {
			$(this).css('z-index', 10);
		}, 
		function () {
			$(this).css('z-index', 9);
		}
	);

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

	// set external link
	$("a.external").attr('target', '_blank');
	$("a[rel*='external']").attr('target', '_blank');
	$(".entry-content a:not([href*='creativecrap.com'],[href^='/'])").attr('rel', 'external').attr('target', '_blank');
	
	$("form").uniform();
	//$("#primary-nav li").hover(mouseenter, mouseleave);
	$(".node-header").addClass('visible');
	
	Shadowbox.init({
		handleOversize: "resize",
		overlayColor: "transaprent",
		overlayOpacity: 0.95,
		animate: false,
		onOpen: function() {
			// fix shadowbox scroll for mobile devices
			if((navigator.userAgent.match(/iPhone/i))||(navigator.userAgent.match(/iPad/i))) {
				clearInterval(timerNav);
				$("#sb-container").css("top", $(window).scrollTop());
				setTimeout(function(){
					$(".site-name").css("top", $(window).scrollTop()-90);
				}, 500);
				$(window).bind('scroll', function() {
					$("#sb-container").css("top", $(window).scrollTop());
					$(".site-name").css("top", $(window).scrollTop());
				});
			}
		},
		onFinish: function() {
			$("#sb-body").addClass('visible');
			$(".site-name").addClass('watermark');
		},
		onChange: function() {
			//$("#sb-body").removeClass('visible');
		},
		onClose: function() {
			$("#sb-body").removeClass('visible');
			$(".site-name").removeClass('watermark');
			if((navigator.userAgent.match(/iPhone/i))||(navigator.userAgent.match(/iPad/i))) {
				$(".site-name").css("top", '0px');
				$(window).unbind('scroll');
				timerNav = setInterval(function() {
					showNavigation(0);
				}, 10000);
			}
		}
	});
	
	//showNavigation(0);
	showNavigation2();
	setTimeout(function() {
		scaleImages();
		nodeMutlilangContent();
		showTagsCloud(0);
	}, 400);
})

function shake(el) {
	var id = Math.ceil(Math.random()*el.length);
	//for (var i=0; i < 3; i++) {
		var i = Math.ceil(Math.random()*10);
		//var op = (i%2==0) ? '+=' : '-=';
		var op = (i%2==0) ? '+' : '-';
		var r = op + Math.floor(Math.random()*10+1) + 'deg';
		//$(el[id]).animate({rotate:r}, 0);
		$(el[id]).css('-moz-transform', 'rotate('+r+')');
		$(el[id]).css('-webkit-transform', 'rotate('+r+')');
		$(el[id]).css('-o-transform', 'rotate('+r+')');
	//};
}

function showNavigation2() {
	$("#navigation nav li").each(function(i, item) {
		var target = $(item);
		for (var i=1; i < 10; i++) {
			target.removeClass('style'+i);
		};
		var s = 'style' + Math.floor(Math.random()*9+1);
		target.addClass(s).removeClass('visible').addClass('visible');
	})
	window.setTimeout(function(){showNavigation2();}, 20000);
}

function showNavigation(i) {
	var r = Math.floor(Math.random()*2+1);
	var op = (r==1) ? 1 : -1;
	var r = Math.floor(Math.random()*5+0) * op;
	var item = $($("#navigation nav li")[i]);
	if (item.length) {
		window.setTimeout(function() {showNavigation(++i);}, 100);
		item.css('-moz-transform', 'rotate('+r+'deg)');
		item.css('-webkit-transform', 'rotate('+r+'deg)');
		item.css('-o-transform', 'rotate('+r+'deg)');
		//item.fadeIn(function() {showNavigation(++i);});
		//item.fadeIn();
		item.addClass('visible');
	}
	else {
		// funky
		window.setTimeout(function(){showNavigation(0);}, 20000);
		//window.setInterval(function() {
		//	shake($("#navigation nav li"));
		//}, 10000);
	}
}
function showTagsCloud(i) {
	var r = Math.floor(Math.random()*2+1);
	var op = (r==1) ? 1 : -1;
	var r = Math.floor(Math.random()*6+0) * op;
	var item = $($(".tags-cloud li")[i]);
	if (item.length) {
		window.setTimeout(function() {showTagsCloud(++i);}, 100);
		item.css('-moz-transform', 'rotate('+r+'deg)');
		item.css('-webkit-transform', 'rotate('+r+'deg)');
		item.css('-o-transform', 'rotate('+r+'deg)');
		//item.css('visibility', 'visible').fadeIn();
		item.addClass('visible');
	}
	else {
		// funky
		//window.setTimeout(function(){showTagsCloud(0);}, 45000);
	}
}

function featuredSlideshow(id) {
	if (id >= $("#featured .slide-thumbs img").length) {
		id = 0;
	}
	$("#featured .slide:visible").removeClass('visible');
	$("#featured .slide-thumbs img:visible").removeClass('visible');
	$("#featured .slide[rel="+id+"]").addClass('visible');
	$("#featured .slide-thumbs img[rel="+id+"]").addClass('visible');
	window.clearTimeout(featuredSlideshowTimer);
	featuredSlideshowTimer = window.setTimeout(function() {
		featuredSlideshow(parseInt(id)+1);
	}, 5000);
}

$.urlParam = function(name){
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (results) {
		return results[1] || 0;
	};
	return 0;
}

function coloration(target) {
	target.each(function(i, item) {
		var lang = $(item).attr('lang');
		$.post("/geshi.php", {"lang":lang, "linenumber":1, "source": $(item).html()}, function(result) {
			if (result) {
				$(item).hide();
				//$(result).find('a').attr('rel', 'external');
				$("<div></div>").addClass("coloration").html(result).insertAfter($(item)); //.find('a').attr('target', '_blank');
			};
		});
	});
}



function redirect() {
	window.location = '/user/?redirect=' + window.location.href;
}

function nl2br(str) {
	var br = '<br />';
	return (str + '').replace(/([^>]?)\n/g, '$1'+ br +'\n');
}

function addslashes(str) {
	return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\u0000/g, "\\0");
}


function validForm(form_id) {
	$(form_id + " :text,:password")
	.each(function() {
		var val = $.trim($(this).val());
		$(this).val(val);
		if (val == $(this).attr("rel")) {
			//$(this).val($(this).attr('rel')).removeClass('uniform-placeholder');
			$(this).val("").removeClass('uniform-placeholder');
		}
	});
	// check require fields
	var valid = true;
	$(form_id + " .require").each(function() {
		$(this).removeClass("uniform-form-invalid");
		//if ($(this).val() == "" || $(this).val() == $(this).attr("rel")) {
		if ($(this).val() == "") {
			$(this).addClass("uniform-form-invalid");
			valid = false;
		};
	});
	if (!valid) {
		$(form_id).uniform();
	};
	//$("#" + form_id + " .x-form-invalid:first").focus();
	//$("#" + form_id + " .x-form-invalid:first").trigger('click');
	return valid;
}

function t(str) {
	if (l10n) {
		var key = str.toLowerCase();
		str = l10n[key] ? l10n[key] : str;
	};
	return str;
}

function mouseenter(e) {
	$(this).addClass('hover');
}

function mouseleave(e) {
	$(this).removeClass('hover');
}

function mouseclick(e) {
	$(this).toggleClass('active');
}

function scaleImages(el) {
	//$("div.img").width($(".column-content").width());
	if (el) {
		//alert(el.css('width'));
		el.css('width', 'auto');
		//alert(el.css('width'));
		el.find('img').css('width', '100%');
	}
	else {
		// adjust all
		$("div.img").css('width', 'auto');
		$("div.img img").css('width', '100%');
	}
}

function loadGalleryThumb(id, data, width, group) {
	var me = $("div.img[rel=" + id + "]");
	var thumb = new Image();
	data.thumb = "/thumb.php?w=" + width + "&zc=0&src=" + data.path;
	$(thumb).load(function() {
		var img = $("<img>").attr('src', data.thumb).attr('alt', data.name);
		var link = $("<a></a>").attr('href', data.path).attr('title', data.name).attr('rel', 'shadowbox[' + group + ']');
		link.wrapInner(img);
		me.prepend(link);
	}).attr('src', data.thumb);
}



function intval(num) {
	//num = $.trim(num);
	num = parseInt(num, 10);
	if (/\D/.test(num)) {
		return 0;
	}
	return num;
}

function replyComment(id) {
	$("#comment-form [name='comment_id']").val(id);
	$("#comment-form textarea").focus();
}

function getComments(page) {
	page = (page) ? page : 1;
	$("#comments-box").fadeOut('fast').load("/node/comment/"+nid+"/?page="+page, function() {
		$("#comments-box").fadeIn('fast');
	});
}

// multi-lang
function nodeMutlilangContent() {
	var lang = $.urlParam('lang');
	$(".content-ml-block").each(function(i, item) {
		var a = $('<a href="javascript:void(0);"></a>').attr('rel', $(this).attr('rel')).text(t('lang-' + $(this).attr('rel'))).click(function() {
			$(".content-ml-block").hide();
			$(".content-ml-block[rel='" + $(this).attr('rel') + "']").fadeIn();
			return false;
		});
		if (i > 0) {
			$(".entry-translation").append(", ");
		};
		$(".entry-translation").append(a);
		$(".entry-translation").show();
	});
	if (lang && $(".content-ml-block[rel='" + lang + "']").length) {
		$(".content-ml-block").hide();
		$(".content-ml-block[rel='" + lang + "']").show();
	};
}
