// JavaScript Document

/**********/

//Gallery page variables

	var total_results_to_load = 200;
	var items_per_page = 9;
	
	var pages_per_request = Math.ceil(total_results_to_load / items_per_page);	

	var curr_gallery_page = 1;
	var requested_gallery_page = 1;
	
	var curr_entry = 0;
	
	var gallery_data;	
	var featured_data;
	var init_story_data;
	
	var gallery_type = "full"; //or sidebar
	
	//to determine whether to show next and prev buttons or not
	var enable_gallery_slideshow = false;

/***********/


function displayEntry(){
	
	showOverlay();	
	showEntryBox();
	
}


function hideEntry(){
	hideEntryBox();
	hideOverlay();
}

function showEntryBox() {
	
	if (enable_gallery_slideshow) {
		enableDisablePrevNextEntryButtons();
	} else {
		//hide prev next buttons
		$("#entry-next-btn").css('display','none');
		$("#entry-prev-btn").css('display','none');
	}
	
	positionEntryBox();
	
	$("#entry-container").css("display", "block");	

	//to resolve title not appearing for first post in IE
	$("#entry-container .title h1").html($("#entry-container .title h1").html());
}

function hideEntryBox() {
	
	$("#entry-container").css("display", "none");	
	
	//to stop video
	$("#entry-container .post_media .video").html("");
	
}

function showOverlay() {
	
	$("#overlay").height($(document).height());
	$("#overlay").css("display", "block");	
}

function hideOverlay() {
	$("#overlay").css("display", "none");	
}

function showMsgOverlay() {
	$("#msg-overlay").height($(document).height());
	$("#msg-overlay").css("display", "block");	
}

function hideMsgOverlay() {
	$("#msg-overlay").css("display", "none");	
}

function positionEntryBox() {
	
	positionDialogInCenter($("#entry-container"));
	
}

function positionDialogInCenter(dialog){
	
	docTop = $(document).scrollTop();
	
	//Get the window height and width
	var winH = $(window).height();
	var winW = $(window).width();
	
	//Set the popup window to center
	dialog.css('top',  (winH / 2 - dialog.height() / 2 ) + docTop );
	dialog.css('left', winW/2 - dialog.width() / 2);
	
}


function prepareHomepageFeature(){
	
	var story_node = featured_data.stories[0];

	$("#featured_post .post_media img").attr("src", story_node.img );
	
	$("#featured_post .title h1").html(story_node.title);
	$("#featured_post .desc").html(story_node.content.substr(0,400) + "...");
	
	$("#featured_post .icon img").attr("src", "images/icons/stamps/homepage/" + story_node.category_id + ".png");
	
	
}

function prepareSidebarFeature(){
	
	var story_node = featured_data.stories[0];

	$("#sidebar-featured-post .post_media img").attr("src", story_node.img );
	
	$("#sidebar-featured-post .title h1").html(story_node.title);
	$("#sidebar-featured-post .desc").html(story_node.content);
	
	$("#sidebar-featured-post .icon img").attr("src", "images/icons/stamps/homepage/" + story_node.category_id + ".png");
	
	$("#sidebar-featured-post .meta").html('<b>'+story_node.display_name+'</b> Posted: '+story_node.submit_date);
	
}


function setEntry(story_node){
	letVote=story_node.voteButtonDate

	$("#entry-container #entry #noVotes").css("visibility", "hidden");
	if (story_node.letVote == "block"){
		$("#entry-container #entry #noVotes").css("visibility", "visible");
	}	
	
	$("#entry-container .vbBig").attr("src", "css/images/buttons/vbBig_" + story_node.voteButtonDate + ".png");

	if (story_node.letVote == "winner"){
		$("#entry-container #entry #noVotes").css("visibility", "visible");
		$("#entry-container .vbBig").attr("src", "css/images/buttons/voteCover.jpg");
$("#entry-container .vbBig").attr("height", "45");
	}
	
	$("#entry-container .icon img").attr("src", "images/icons/stamps/postcards/" + story_node.category_id + ".png");
	
	$("#entry-container .title h1").html(story_node.title);
	$("#entry-container .desc").html(story_node.content);
	$("#entry-container span.votes").html(story_node.votes);
	$("#entry-container span.likes").html(story_node.likes);
	$("#entry-container span.entry-num span.num").html(story_node.story_id);
	$("#entry-container span.entry-date").html(story_node.submit_date);
	$("#entry-container span.entry-by").html(story_node.display_name);
	
	//reset photo box
	$("#entry-container .post_media .photo").css("display", "none");
	
	//reset video box
	$("#entry-container .post_media .video").css("display", "none");
	$("#entry-container .post_media .video").html("");
	
	//display photo or video
	if (story_node.is_image){
		
		//show pic
		$("#entry-container .post_media img").attr("src", "" ); //reset to blank pic before loading real pic
		$("#entry-container .post_media img").attr("src", story_node.img_hqp );
		$("#entry-container .post_media .photo").css("display", "block");
		
	} else {
		
		//show video box
		$("#entry-container .post_media .video").css("display", "block");
		
		video_id = story_node.video_id;
		
		if(video_id) {
		//embed youtube video
			$("#entry-container .post_media .video").html('<object width="316" height="213"><param name="movie" value="http://www.youtube.com/v/'+video_id+'&hl=en_GB&fs=1&rel=0"></param><param name="wmode" value="transparent"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+video_id+'&hl=en_GB&fs=1&rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="316" height="213" wmode="transparent"></embed></object>');

		}
	}
	
	$("#entry-container a.votes").unbind('click'); //remove prev click function
	$("#entry-container a.votes").click(function(){
		submitVote( story_node, story_node.story_id, $(this).children("span.votes") );
		return false;
	});
	
	$("#entry-container a.likes").unbind('click'); //remove prev click function
	$("#entry-container a.likes").click(function(){
		submitLikes( story_node, story_node.story_id, $(this).children("span.likes"), $(this) );
		return false;
	});
	
	setupEntrySharingButtons(story_node.story_id, story_node.title);
	
}

function setupEntrySharingButtons(story_id, story_title){	

	share_url = "http://" + location.hostname + "/index.asp?init_story=" + story_id;
	share_title = story_title;
	
	//$("#entry-sharing-facebook").attr("href", "http://www.facebook.com/sharer.php?u="+share_url+"&t="+story_title);
	
	$("#entry-addthis-toolbox").attr("addthis:url", share_url);
	$("#entry-addthis-toolbox").attr("addthis:title", story_title);
	
	addthis.toolbox("#entry-addthis-toolbox");
	
}


function submitLikes(story_node, story_id, likes_count_node, likes_btn_node) {	
	
	//submit vote
	//randomizer
	rand = Math.random();
		
	 $.getJSON("process_likes.asp?rand=" + rand + "&StoryID=" + story_id,
			   
        function(data, textStatus){
	  
	  		if (data.like_status == "success") {
			
				//vote successful
				msgDialog("Thank you for liking this");
				story_node.likes = data.likes;
				likes_count_node.html(data.likes);
				
				//disable likes button
				likes_btn_node.unbind('click');
				likes_btn_node.click(function(){
					 msgDialog("You have already liked this");
					 return false;
				});
				
			} else if (data.like_status == "not_logged_in") {			
				msgDialog("Sorry, you must login to like");
			} else {
				//some other status	
			}
		  
        });	
		
}


function submitLoginForm(){

	var u = $("#login-form-username").val();
	var p = $("#login-form-password").val();	
   
	if ( u && p ) {	
		$.post("login_request.asp", { username: u, password: p }, loginResponse, "text");
	} else {
		msgDialog("Please enter your email address and password.");
	}
	return false;
}

function loginResponse(data, textStatus) {
	
	if (textStatus == "success") {
		if (data == "login_success") {
			window.location.reload();
		} else {
			//login failed
			msgDialog("Sorry, you have entered an invalid email or password.");
		}
	} else {
		//script failed	
		msgDialog("Sorry, an error occured. Please try again.");
	}
	
}


function submitVote(story_node, story_id, vote_count_node) {	
	
	//submit vote
	//randomizer
	rand = Math.random();
		
	 $.getJSON("process_voting.asp?rand=" + rand + "&StoryID=" + story_id,
			   
        function(data, textStatus){
	  
	  		if (data.vote_status == "success") {
			
				//vote successful
				msgDialog("Thank you for your vote");
				story_node.votes = data.votes;
				vote_count_node.html(data.votes);
				
			} else if (data.vote_status == "voted_today") {			
				msgDialog("Sorry, you have already voted. You can only vote once per day.");
			} else if (data.vote_status == "not_logged_in") {			
				//alert("Sorry, you must login to vote");
				msgDialog("Sorry, you must login to vote");				
			} else if (data.vote_status == "period") {			
				//alert("Sorry, you must login to vote");
				msgDialog("Voting starts in January");		
			} else {
				//some other status	
			}
		  
        });	
	
				var axel = Math.random() + "";
				var a = axel * 1000000000000000000;
				var tag_url = new Image();
				tag_url.src = 'http://fls.doubleclick.net/activityi;src=1774243;type=trave073;cat=trave277;ord=1;num='+a+'?';
}

function msgDialog(msg){	
	$("#msg-dialog span.msg").html(msg);	
	positionDialogInCenter($("#msg-dialog"));
	showMsgOverlay();
	displayMsgBox();
}

function closeMsgDialog(){	
	hideMsgBox();
	hideMsgOverlay();
}

function displayMsgBox(){
	$("#msg-dialog").css("display", "block");	
}

function hideMsgBox() {
	$("#msg-dialog").css("display", "none");
}


function setEntryFromRowData(){
	
	var entry_index = curr_entry;
	
	var story_node = gallery_data.stories[entry_index-1];		
		
	setEntry(story_node);	
	
}


function setEntryFromFeaturedPost(){
	
	var story_node = featured_data.stories[0];
			
	setEntry(story_node);

}

function displayInitStory(story_id){
	
	loadInitStory(story_id);
	
}


function initGallery () {
	
	programGalleryBtns();
	
	programEntryBtns();
	
	loadGalleryJSON();
	
}

function initSidebarGallery(){
		
	total_results_to_load = 6;
	gallery_type = "sidebar";
			
	loadGalleryJSON();
	
	programEntryBtns();	
	
}


function programEntryBtns () {
	
	$("#entry-next-btn").click(function(){

		num = curr_entry + 1;
		
		if (num <= gallery_data.stories.length) {
			
			curr_entry = num;			
			setEntryFromRowData();
			
		}
		
		enableDisablePrevNextEntryButtons();
		
	});	
	
	
	$("#entry-prev-btn").click(function(){

		num = curr_entry - 1;
		
		if (num > 0) {
			
			curr_entry = num;			
			setEntryFromRowData();
		} 
		
		enableDisablePrevNextEntryButtons();
		
	});	
	
}


function enableDisablePrevNextEntryButtons(){
	
	if (curr_entry > 1) {
		$("#entry-prev-btn").css('display','block');			
	} else {
		$("#entry-prev-btn").css('display','none');		
	}	
	
	if (curr_entry < gallery_data.stories.length) {
		$("#entry-next-btn").css('display','block');	
	} else {
		$("#entry-next-btn").css('display','none');		
	}	
	
}



function loadGallery(){
	
	alert("load gallery");
	
	//loadGalleryXML();
	
	//prepare parameters	
	//query_parameters = getSearchGalleryParameters();
	
	//attach random to avoid caching
	//query_parameters += "&rand=" + Math.random();
	
	//displayGalleryLoading();
	
	//alert("ppr "+pages_per_request);
	
	//$("#gallery-dyn-content").load("/searchGallery.asp", query_parameters, galleryLoadCallback );

}

function loadGalleryXML () {
	
	//prepare parameters	
	//query_parameters = getSearchGalleryParameters();
	
	//alert(query_parameters);
	
	$.ajax({
		type: "GET",
		url: "gallery.xml",
		dataType: "xml",
		success: function(data){
			galleryXMLLoaded();
		}
	});

}

function loadGalleryJSON () {

	displayGalleryLoading();

	//prepare parameters	
	query_parameters = getSearchGalleryParameters();
	
	//randomizer
	rand = Math.random();
		
	 $.getJSON("loadGalleryJSON.asp?rand=" + rand + "&start=1&end=" + total_results_to_load + "&" + query_parameters,
        function(data, textStatus){
	  
	  		hideGalleryLoading();
	  
	  		if (data.stories.length > 0) {
			
				gallery_data = data;
				
				curr_gallery_page = 1;
				requested_gallery_page = 1;
				
				if (gallery_type == "full") {
					loadGalleryPage();
				} else if (gallery_type == "sidebar") {
					loadGallerySidebar();	
				}
				
				afterInitialGalleryLoad();				
				
			} else {
			
				msgDialog("Sorry, there were no results for this query.");

			}
		  
        });

}


function loadInitStory(story_id) {
		
	$.getJSON("loadFeaturedJSON.asp?rand="+Math.random()+"&id=" + story_id,
		function(data){  
			
			if (data.stories.length > 0) {					
			
				init_story_data = data;
			
				var story_node = init_story_data.stories[0];		
				
				setEntry(story_node);	 
				displayEntry();
				
			}
			
	});
	
}

function loadSidebarFeature() {
	
	$.getJSON("loadFeaturedJSON.asp?rand="+Math.random(),
        function(data){
	  
		  	featured_data = data;
			
			prepareSidebarFeature();
		  
        });

	$("#sidebar-featured-post").click(function(){
									  
		setEntryFromFeaturedPost();	
		
		enable_gallery_slideshow = false;
		displayEntry();				
		
	});
	
}

function loadHomepageFeature() {

	$.getJSON("loadFeaturedJSON.asp?rand="+Math.random(),
        function(data){
	  
		  	featured_data = data;
			
			prepareHomepageFeature();
		  
        });

	

	$("#featured_post").click(function(){
									  
		setEntryFromFeaturedPost();		
		
		enable_gallery_slideshow = false;
		displayEntry();				
		
	});
	
}


function loadGallerySidebar() {
	
	var gallery_html = "";
	
	var items_added = false;

	
	for (i=1; i<=6 && i <= gallery_data.stories.length ; i++){	
	
		story_node = gallery_data.stories[i-1];
	
		gallery_item_html = 	'<div class="entry-thumb-1" entry_index="' + i + '" story_id="'+story_node.story_id+'">';
		gallery_item_html += 				'<img src="' + story_node.img_sml + '" />';
		gallery_item_html += 	'</div>';
	
	
		gallery_html += gallery_item_html;
		
	}
	
	gallery_html += 	'<br clear="all" />';
	
	$("#sidebar-gallery").html(gallery_html);
	
	programSidebarGalleryThumbs();
		
}

function loadGalleryPage() {

	var page = requested_gallery_page;
	
	var start = ((page * items_per_page) - items_per_page ) + 1;
	var end = page * items_per_page;
	
	var gallery_html = "";
	
	var items_added = false;

	
	for (i=start; i<=end && i <= gallery_data.stories.length ; i++){	
		
	
		items_added = true;
		
		story_node = gallery_data.stories[i-1];
		
		var story_type = "";
		
		if (story_node.is_image){
			story_type = "photo"
		} else {
			story_type = "video";	
		}
		
		gallery_item_html = 	'<div class="gallery-item" entry_index="' + i + '" story_id="'+story_node.story_id+'">';
		gallery_item_html += 		'<div class="button">';
		gallery_item_html += 			'<div class="thumb">';
		gallery_item_html += 				'<img src="' + story_node.img + '" />';
		gallery_item_html += 				'<div class="story_type '+ story_type +'"></div>';
		gallery_item_html += 			'</div>';
		gallery_item_html += 			'<h2>' + story_node.title + '</h2>';
		gallery_item_html += 			'<h3>' + story_node.content.substr(0, 50) + '...</h3>';
		gallery_item_html += 		'</div>';
		if (story_node.letVote == "none"){
			gallery_item_html += 		'<a href="#" class="vote" ></a>';
		}
		else{
			gallery_item_html += 		'<img class="" src="/css/images/buttons/vbSmall_' + story_node.voteButtonDate + '.png" width="81" height="20" />';
		}
		gallery_item_html += 		'<a href="#" class="like">' + story_node.likes + '</a>';
		gallery_item_html += 		'<br clear="all" />';
		gallery_item_html += 	'</div>';
	
		gallery_html += gallery_item_html;
		
		if (i % 3 == 0 ) {
			gallery_html += '<div class="dividor blue"></div>';
		}
		/*
		<div class="gallery-item" row="<%=row%>">
                
            <div class="button">
                <div class="thumb">
                <img src="<%=image_thumb%>" />
                </div>
                <h2><%=story_title%></h2>
                <h3><%=story_content%></h3>
            </div>
            <a href="" class="vote"></a>
            <a href="" class="like"><%=likes%></a>
            <br clear="all" />
        </div>
		*/
	}
	
	if (items_added) {
		$("#gallery-dyn-content").html(gallery_html);
		curr_gallery_page = page;
		programGalleryThumbs();
	} else {
		
	}
	
	
}


function galleryXMLLoaded(){

}

function galleryLoadCallback () {	
	hideGalleryLoading();
	programGalleryThumbs();
	afterGalleryLoad();
}

function programSidebarGalleryThumbs(){
	$("#sidebar-gallery .entry-thumb-1").click(function() {
		//galleryItemClicked( $(this) );	
		index = $(this).attr("entry_index");
		window.location = "gallery.asp?init_spot=" + index;
	});
}

function programGalleryThumbs() {
	
	$(".gallery-item .button").hover(
		function () {
			$(this).parent().addClass("over");				
		}, 
		function () {
			$(this).parent().removeClass("over");	
		}
	);	
	
	
	$(".gallery-item .vote").unbind('click');
	$(".gallery-item .vote").click(function() {
		entry_index = parseInt($(this).parent().attr("entry_index"));
		story_node = gallery_data.stories[entry_index-1];
		submitVote( story_node, $(this).parent().attr("story_id"), null );
		return false;
	});
	
	$(".gallery-item .like").unbind('click'); //remove prev click function
	$(".gallery-item .like").click(function() {
		entry_index = parseInt($(this).parent().attr("entry_index"));
		story_node = gallery_data.stories[entry_index-1];
		submitLikes( story_node, $(this).parent().attr("story_id"), $(this), $(this) );
		return false;		
	});
			
	$(".gallery-item .button").click(function() {
	 	enable_gallery_slideshow = true;
		galleryItemClicked( $(this).parent() );		
	});
	
}


function galleryItemClicked(entry){
	
	entry_index = parseInt(entry.attr("entry_index"));	
	if (entry_index) {
		curr_entry = entry_index;
	}
	setEntryFromRowData();
	displayEntry();
	
}

function programGalleryBtns() {
	
	$("#gallery-search-btn").click(function() {
		
			loadGalleryJSON();
		
		return false;
	});
	
	$("#gallery-prev-btn").click(function() {
		galleryPrevBtnClicked();
		return false;
	});
	
	$("#gallery-next-btn").click(function() {
		galleryNextBtnClicked();
		return false;
	});

}


function galleryNextBtnClicked() {
	requested_gallery_page = curr_gallery_page + 1;
	loadGalleryPage();
}


function galleryPrevBtnClicked() {
	requested_gallery_page = curr_gallery_page - 1;
	if (requested_gallery_page < 1) {
		requested_gallery_page = 1;
	}
	loadGalleryPage();	
}


function getSearchGalleryParameters () {
	
	query_parameters = "";
	
	var gallery = $.query.get('gallery');
	if (gallery) {	
		query_parameters += "order=" + gallery;
	} else {
		query_parameters += "order=recent";
	}
	
	//keywords
	
	keywords = $("#gallery-search-txt").val();
	
	if (keywords && keywords != "SEARCH") {
		query_parameters += "&q=" + keywords;
	}
	
	return query_parameters;
	
}

function displayGalleryLoading() {
	$("#gallery-loading").css("visibility","visible");
}

function hideGalleryLoading() {
	$("#gallery-loading").css("visibility","hidden");
}

function previewStoryClicked(title, cat_id, desc, display_name){

	$("#entry-container .icon img").attr("src", "images/icons/stamps/postcards/" + cat_id + ".png");
	
	$("#entry-container .title h1").html(title);
	$("#entry-container .desc").html(desc);
	$("#entry-container span.votes").html("0");
	$("#entry-container span.likes").html("0");
	$("#entry-container span.entry-num span.num").html("0");
	$("#entry-container span.entry-date").html(dateFormat("shortDate"));
	
	//set display name on post page
	if (display_name) {
		$("#entry-container span.entry-by").html(display_name);		
	} else {
		$("#entry-container span.entry-by").html("Your Name");
	}
	
	//show preview pic
	$("#entry-container .post_media img").attr("src", "images/post/video_photo_preview.jpg" );
	$("#entry-container .post_media .photo").css("display", "block");

	//reset video box
	$("#entry-container .post_media .video").css("display", "none");
	$("#entry-container .post_media .video").html("");
	
	$("#entry-container a.votes").unbind('click'); //remove prev click function
	$("#entry-container a.votes").click(function(){
		return false;
	});
	
	$("#entry-container a.likes").unbind('click'); //remove prev click function
	$("#entry-container a.likes").click(function(){
		return false;
	});

	displayEntry();
	
}

function loadTravelTips(){

	//travelguard
	//var twitter_url = "http://twitter.com/status/user_timeline/18202481.json?rand="+Math.random()+"&count=3&callback=?";	 
	
	//tgnewsfeed
	var twitter_url = "http://twitter.com/status/user_timeline/94344379.json?rand="+Math.random()+"&count=3&callback=?";	 	
	
	$.getJSON(twitter_url, 	
			  
		function(data){ 
		
			 var travel_tips_html = "";
			 
			 $.each(data, function(i, item) { 
						
				var tip_link_pos = item.text.lastIndexOf('http');
				var tip_link_pos_end = item.text.substr(tip_link_pos).indexOf(" ");

				var tip = item.text;


				if (tip_link_pos > 0) {
					var tip_link = item.text.substr(tip_link_pos).substr(0,tip_link_pos_end);
				}
				else{
					var tip_link = "N";
				}
				
				var plus_pos = item.created_at.indexOf('+');	
				date_without_gmt = item.created_at.substr(0, plus_pos-1 ) + item.created_at.substr(plus_pos+5); 

temp = date_without_gmt
var h2 = temp.indexOf(':');	
shortString = temp.substr( 0, h2 )
var h1 = shortString.lastIndexOf( ' ' );

var part1 = shortString.substr( 0, h1 )
var newTime = temp.substr( h1, h2-h1 )-5
var part2 = temp.substr( h2, 15 )

date_without_gmt = (part1+" "+newTime+part2)				

				//var tip_date = $.timeago(date_without_gmt);
				var tip_date = dateFormat(date_without_gmt, "dddd, mmmm d, yyyy h:MM TT");
				//var tip_date = dateFormat(item.created_at.substr());
				
				if (!tip_date) {
					tip_date = "";	
				}
				
				var tip_html = "";
				tip_html += '<div class="tip">';
if (tip_link != "N") {
	tip_html += '<a href="'+tip_link+'" class="tip" target="_blank">';
}
tip_html += tip;
if (tip_link != "N") {
	tip_html += '</a>';
}
				//tip_html += '<a href="'+tip_link+'">'+tip_link+'</a>';
				tip_html += '<span class="meta">'+tip_date+'</span>';
				tip_html += '</div>';
				
				travel_tips_html += tip_html;
				
				travel_tips_html += '<div class="dividor black" style="margin: 9px 0 9px 0"></div>';
				
            }); 
			 
			$("#travel-tips-content").html(travel_tips_html);
			
		}
	); 
	
}

/* function regular select box */
/*
function galleryOrderChanged(){
	
	document.getElementById('sidebar-gallery-form').submit();
	
}
*/


/* function for sexy combobox */
function galleryOrderChanged(order){

	if (order) {
		window.location = "gallery.asp?gallery=" + order;	
	}
	
}