var baseUrl = '';
var originalController = '';

$(document).ready(function()
{
	baseUrl = $("#baseUrl").val();
	originalController = $("#originalController").val();

	$(document).pngFix();

	$("#menu").show();

	initImagePreview();

	// $("#sumbitVote").bind("click", showPollResults);
		// $("#showResults").bind("click", showPollResults);
		// setTimeout('animatePollGraph()', 500);

		// $(".pagination a").live("click", initPagination);

		$('#carousel').jcarousel(
		{});

		// Create the Menu
		jQuery('#menu').slidermenu();

		initActiveMenuLink();

		initTestimonials();

		$("#dialog").dialog(
		{
			autoOpen : false,
			show : "blind",
			hide : "blind",
			modal : true
		});

		if (originalController == 'index')// homepage
		{
			initNewsletterForm();
		}

		else
			if (originalController == 'page' || originalController == 'photo')
			{
				initURLPreview();
				// initGalleryAnimation();

				// $('.categories_control a:first-child').focus();
				// $('.sort_control a:first-child').focus();

				$('.categories_control a').bind("click", initGalleryFilterAnimation);

				$('.sort_control a').bind("click", initGallerySortAnimation);
			}
	});

function initGalleryFilterAnimation(e)
{
	$.ajax(
	{
		url : $(this).attr('href'),
		beforeSend : function()
		{
			$("#loading").show();
		},
		success : function(data)
		{
			$('.photo_list').quicksand($(data).find('li'),
			{
				attribute : 'id',
				easing : 'easeInOutQuad',
				adjustHeight : 'dynamic'
			});
			
			$("#loading").hide();
		}
	});

//	$.get($(this).attr('href'), function(data)
//	{
//		$('.photo_list').quicksand($(data).find('li'),
//		{
//			attribute : 'id',
//			easing : 'easeInOutQuad',
//			adjustHeight : 'dynamic'
//		});
//	});

	$('.categories_control a').removeClass("active");
	$(this).addClass("active");

	e.preventDefault();
}

function initGallerySortAnimation(e)
{
	// get the first collection
	var list = $('.photo_list');

	// clone applications to get a second collection
	var data = list.clone();

	var sortBy = $(this).attr("id");

	// attempt to call Quicksand on every form change

	var filteredData = data.find('li');

	if (sortBy == 'sort_title')
	{
		var sortedData = filteredData.sorted(
		{
			reversed : false,
			by : function(v)
			{
				console.log($(v).find('.photo_title').text().toLowerCase());
				return $(v).find('.photo_title').text().toLowerCase();
			}
		});
	}
	if (sortBy == 'sort_date_new')
	{
		var sortedData = filteredData.sorted(
		{
			reversed : true,
			by : function(v)
			{
				return $(v).find('.created_on').text();
			}
		});
	}
	if (sortBy == 'sort_date_old')
	{
		var sortedData = filteredData.sorted(
		{
			reversed : false,
			by : function(v)
			{
				return $(v).find('.created_on').text();
			}
		});
	}
	// finally, call quicksand
	list.quicksand(sortedData,
	{
		duration : 800,
		attribute : 'id',
		easing : 'easeInOutQuad',
		useScaling : false
	});

	$('.sort_control a').removeClass("active");
	$(this).addClass("active");

	return false;
}

function initURLPreview()
{
	var apiKey = 'UlT4Q03vb2dj';

	$('a.websnapr').each(function()
	{
		// var websnapr_hash = 32578098846;
			// Grab the URL from our link
			var url = encodeURIComponent($(this).attr('href')),

			// Create image thumbnail using Websnapr thumbnail service
			thumbnail = $('<img />',
			{
				src : 'http://images.websnapr.com/?url=' + url + '&key=' + apiKey + '&hash=' + encodeURIComponent(websnapr_hash),
				alt : 'Loading thumbnail...',
				width : 202,
				height : 152
			});

			// Setup the tooltip with the content
			$(this).qtip(
			{
				content : thumbnail,
				position :
				{
					my : 'top center',
					at : 'bottom center',
					viewport : $(window)
				// Attempt to keep it on screen at all times
				},
				style :
				{
					classes : 'ui-tooltip-thumbnail ui-tooltip-shadow'
				}
			});
		});
}

function initActiveMenuLink()
{
	// var currentUrl = window.location.pathname;
	var currentUrl = $(location).attr('href');
	// alert(currentUrl);
	// alert($("#menu a").attr("href"));
	// alert(currentUrl.indexOf($("#menu a").attr("href")))

	$.each($("#menu a"), function()
	{
		var url = $(this).attr("href");
		// alert(url);
			if (currentUrl.indexOf(url) != -1)
			{
				$(this).children("span").addClass("active");
			}
		});

	// if($("#menu a").attr("href").is(substr from the window.location))
}

function initTestimonials()
{
	$("#testimonials").cycle(
	{
		fx : 'fade',
		speed : 1000,
		timeout : 3000,
		pause : 1,
		random : 0
	});
}

function initNewsletterForm()
{
	$('#newsletterForm').ajaxForm(
	{
		url : baseUrl + "/admin/newsletter-subscriber/create",
		beforeSubmit : showNewsletterSubscribtionRequest,
		success : showNewsletterSubscribtionResponse,
		type : 'post',
		resetForm : true,
		clearForm : true
	});

	validateNewsletterForm();
}

function showNewsletterSubscribtionRequest(arr, $form, options)
{
	$("#newsletterForm #submit").hide();
	$("#newsletterForm #loading").show();
	return $('#newsletterForm').validate().form();
}

function validateNewsletterForm()
{
	$("#newsletterForm").validate(
	{
		rules :
		{
			subscriber_name :
			{
				required : true
			},
			subscriber_email :
			{
				required :
				{
					depends : function(element)
					{
						return $("#subscriber_mobile").val() == '';
					}
				},
				email : true
			},
			subscriber_mobile :
			{
				required :
				{
					depends : function(element)
					{
						return $("#subscriber_email").val == '';
					}
				}
			}
		},
		messages :
		{
			subscriber_name :
			{
				required : "<div><span class='error'>* please enter your name.</span></div>"
			},
			subscriber_email :
			{
				email : "<div><span class='error'>* please enter a valid email.</span></div>",
				/*
				 * remote : "<div><span class='error'>* this email is already
				 * subscribed.</span></div>",
				 */
				required : "<div><span class='error'>* please enter your email or your mobile.</span></div>"
			},
			subscriber_mobile :
			{
				required : "<div><span class='error'>* please enter your mobile or your email.</span></div>"
			}
		}
	});
}

function showNewsletterSubscribtionResponse(responseText, statusText, xhr, $form)
{
	$("#dialog").html(responseText);
	$("#dialog").dialog("open");

	$("#newsletterForm #loading").hide();
	$("#newsletterForm #submit").show();

	return false;
}

function initPagination()
{
	var link = $(this);
	var container = link.parents('#main_content');

	$.ajax(
	{
		type : "POST",
		url : link.attr('href'),
		success : function(result)
		{
			console.log(result);
			container.html(result);
		},
		error : function(e1, e2, e3)
		{
			alert("error");
		}
	});

	return false;
}

function initImagePreview()
{
	$('a[rel^=lightbox]').lightBox(
	{
		fixedNavigation : true,
		overlayBgColor : '#000',
		overlayOpacity : 0.6,
		containerBorderSize : 10,
		containerResizeSpeed : 400,
		txtImage : 'Image',
		txtOf : 'of',
		keyToClose : 'c'
	});
	// console.log($('a[rel^=lightbox]').html())
}

function showPollResults()
{
	var pollId = $("#pollId").val();
	var pollResult = $(".poll_item input:radio:checked").val();

	$.ajax(
	{
		type : "POST",
		url : baseUrl + "/poll/results",
		data : "pollId=" + pollId + "&pollResult=" + pollResult,
		success : function(result)
		{
			$("#poll").html(result);
			setTimeout('animatePollGraph()', 500);

			if (pollResult != undefined)// the user selevted a poll answer
		{
			var cookieName = "poll_" + pollId;
			createCookie(cookieName, 'poll_done', 30);
		}
	},
	error : function(e1, e2, e3)
	{
	}
	});
}

function animatePollGraph()
{
	// $(".pollBar.hidden").show("slow");
}

