/**
	@class
	@description Analytics
*/
REFRESH_APP.analytics = {
	init: function() {
		var category = $("span.category-name").text();
		//facebook link
		$("a.install-the-application").click(function() {
			pageTracker._trackEvent('Social','install facebook application link',category);
		});
		
		//widget click
		$("#widget_edit_link").click(function() {
				pageTracker._trackEvent('Social','get embed widget',category);
		});
		
		$("a.widget-button").click(function() {
			$('#widget_edit_link').trigger('click');	
		});
		
		// Max tout in the middle of the page 
		$("#cta-max-middle").click(function() {
			pageTracker._trackEvent('Click Thru', 'Banner Click', 'Pepsi Max');
		});
	}
}

/**
	@class
	@description PNG Fix
*/
REFRESH_APP.pngFix = {
	init: function() {
		//$('.bg-awardee').ifixpng().css({}).click(function(){ location.href = "/myidea/edit"; }).hover(function() { $(this).find("a").css("text-decoration","underline");}, function() { $(this).find("a").css("text-decoration","none");}); 
		$('.grant-awardee').ifixpng();
	}
}

/**
	@class
	@description funded idea page login
*/
REFRESH_APP.fundedideaLogin = {
	init: function() {
		
		if($("#facebook-logout").length != 0 || $("#profile-pcna").length != 0) {
			if($(".is-funded").length > 0) {
				REFRESH_APP.fundedideaLogin.isIdeaOwner();
				REFRESH_APP.isFunded.init();
			}
		} else {
			if($(".is-funded").length > 0) {
				var moneyTier = $("#monetary-tier").text();
				var topCategoryText = "10";
				if(moneyTier.indexOf("250") != -1) {
					var title = $("h1 span").text();
					topCategoryText = "2";
					
					if(title.indexOf("Joyful") != -1) {
						topCategoryText = "3";
					}
				}
				
				var monetaryTierText = $("h1 span").text();
				var awardeeClass = "bg-awardee";
				if(monetaryTierText.length > 50) {
					awardeeClass = "bg-awardee-large";
				}
				$("#badge").before('<div id="funded-logged-out" class="' + awardeeClass + '">This project finished in the <a href="/grant-recipients/">top ' + topCategoryText + '</a> in ' + $("#granted-month").text() + ', 2010 <span>' + monetaryTierText + ' was awarded $' + $("#monetary-tier").text() + '!</span></div>');
							
				REFRESH_APP.isFunded.init();
			}			
		}
		REFRESH_APP.pngFix.init();
	},
	isIdeaOwner: function() {
	
		var ideaid = $(".view-all-funded-ideas").attr("rel");
			
		$.ajax({
			url: "/ideadetails/ideaowner/",
			type: "POST",
			data: {id:ideaid},
			success: function(data){
				if(data == "is-idea-owner") {
					$("#badge").before('<div id="funded-logged-in" class="bg-awardee">Welcome back ' + $("h1 span").text() + '<span><a href="/myidea/edit">Edit your idea page</a>&nbsp;|&nbsp;<a class="guide" href="/docs/PRP_Guidebook_web_003.pdf">Download your toolkit (pdf)</a></span></div>');
				} else {
					var monetaryTierText = $("h1 span").text();
					var moneyTier = $("#monetary-tier").text();
					var topCategoryText = "10";
					
					if(moneyTier.indexOf("250") != -1) {
						topCategoryText = "2";
					}
					
					var awardeeClass = "bg-awardee";
					if(monetaryTierText.length > 70) {
						awardeeClass = "bg-awardee-large";
					}
					
					$("#badge").before('<div id="funded-logged-out" class="' + awardeeClass + '">This project finished in the <a href="/grant-recipients/">top ' + topCategoryText + '</a> in ' + $("#granted-month").text() + ', 2010 <span>' + monetaryTierText + ' was awarded $' + $("#monetary-tier").text() + '!</span></div>');
					
				
				}
				REFRESH_APP.pngFix.init();
			},
			error: function() {
			}
		});
		
	}	
}

REFRESH_APP.isFunded = {
	init: function() {
		$('a.learn-more').click(function(e) {
			e.preventDefault();
			var learnMore = $('#learn-more-container');
        	if(learnMore.is(":hidden")) {
        		if($.browser.msie && $.browser.version == 6) {
        			learnMore.show().addClass("show");
        		} else {
            		learnMore.slideDown("slow").addClass("show");
            	}
            } else {
        		if($.browser.msie && $.browser.version == 6) {
        			learnMore.hide().addClass("hide");
        		} else {
                	learnMore.slideUp("slow").addClass("hide");
            	}            
            }
        });
	}
}

/**
	@class 
	@class
	@description Left Sidebar
*/
REFRESH_APP.leftSideBar = {
	init: function() {
		this.setHeight();
	},
	setHeight: function() {
		$('div.inner-content,#sidebar-left,#sidebar-right').equalHeight();
		//$("#sidebar-left").height($("#sidebar-right").height());
		//$("#sidebar-right").height($(".inner-content").height());
	}
}

/**
	@class
	@description Bit.ly url shortener for idea url
*/
REFRESH_APP.bitly = {
	init: function() {
		this.shorten($("#idea-url").val());
	},
	shorten: function(longurl) {
	
		var href = "http://api.bit.ly/shorten?version=2.0.1&login=pepsirefresh&apiKey=R_e27934e090d1710aa265dbc4ab16ea25&longUrl=" + longurl + "&callback=?";
		if(REFRESH_APP.general.ssl) href = "/proxy/bitly?url=" + longurl + "&callback=?";

			$.ajax({
				url: href,
				type: "GET",
				dataType: "text",
				success: function(json){
					var json = $.parseJSON(json);
					
					var shortUrl = json.results[longurl].shortUrl;
					var promoteUrl = $(".promote-url");
					if(json.errorCode == 0) {
						promoteUrl.each(function() {

							$(this).val(shortUrl);
						});
					} else if(json.errorCode == 208) {
						promoteUrl.each(function() {
							$(this).val(longurl);
						});

					} else {
						promoteUrl.each(function() {
							$(this).val(longurl);
						});

					}
				},
				error: function() {
					//show long url
						$(".promote-url").each(function() {
							$(this).val(longurl);
						});
				}
			});
	}
}

/**
	@class
	@description PepsiCo affiliated popup
*/
REFRESH_APP.affiliated = {
	init: function() {
		$("div.affiliated img, div.affiliated a").click(function(e) {
			e.preventDefault();
			REFRESH_APP.affiliated.show();
		});
	},
	/**
		Show popup
	*/
	show:function() {

		$.fn.colorbox({
			href:'/ideadetails/pepsico',
			scrolling:false,
			open:true,
			speed:300
		});

	}
}

/**
	@class
	@description Given an identifier, countsdown the number of characters allowed for a particular textfield; Expects 'textarea' and '.count' contained within the identifier.
*/
REFRESH_APP.charCountdown = {

	/**
		Initializes charCountdown
	*/
	init: function(x) {
		
		if ( $(x).length ){
			$(x).each( function() {
				var set = $(this).parents('fieldset');
				var counter = $(this).find('.count');
				var countLimit = parseInt(counter.html() );
				var textarea = $("textarea");
				REFRESH_APP.charCountdown.updateCount(counter, textarea, countLimit);
				REFRESH_APP.charCountdown.watchText(counter, textarea, countLimit);
			});
		}
	},

	/**
		Monitors the textarea via 'keyup'
	*/
	watchText: function(counter, textarea, countLimit) {
		textarea.keyup( function() {
			REFRESH_APP.charCountdown.updateCount(counter, textarea, countLimit);
		});
	},

	/**
		Updates the character count limit on screend
	*/
	updateCount: function(counter, textarea, countLimit) {
		var shortenText = '<span class="shorten"> (please shorten)';
		var text = $(textarea).val();
		var newNum = countLimit - text.length;
		var p = counter.parents('p.textarea-help');
		counter.html( newNum );
		if (newNum < 0) {
			p.addClass('bad-count');
			if (!p.find('span.shorten').length) {
				p.append(shortenText);
			}
		} else if (p.hasClass('bad-count')) {
			p.removeClass('bad-count').find('span.shorten').remove();
		}
	}

};


/**
	@class
	@description Idea Page
*/
REFRESH_APP.ideaPage = {
	getIdeaID: function() {
		var ideaID = $("#comments").attr("rel");
		return ideaID;
	}
}

/**
	@class
	@description Google Maps
*/
REFRESH_APP.map = {
	init: function() {
		
		var category = $("#content").attr("class");
		category = category.split(" ");
		var iconSrc = "";
		switch(category[0]) {
		  	case "planet":
		  		iconSrc = "marker-planet";
		  		break;
			case "neighborhoods":
				iconSrc = "marker-neighborhoods";
				break;
			case "food":
				iconSrc = "marker-food";
				break;
		  	case "health":
		  		iconSrc = "marker-health";
		  		break;
		  	case "arts":
		  		iconSrc = "marker-arts";
		  		break;
		  	case "education":
		  		iconSrc = "marker-education";
		  		break;
	  	}

	  	this.show(iconSrc);

	},
	show: function(iconSrc) {
		
	   if (GBrowserIsCompatible()) { 
      	var map = new GMap2(document.getElementById("map"));

        map.setUIToDefault();

        var geo = new GClientGeocoder();
        var zip = $("#map-zip").val();
		// hardcoded for PEP-1878
        var q = $('#idea-location').text() + ", USA";
        geo.getLocations(q, function (result) {
        	if (result.Status.code == G_GEO_SUCCESS) {
            	var p = result.Placemark[0].Point.coordinates;

             	var icon = new GIcon();
				icon.image = "/images/idea/" + iconSrc + ".png";
				icon.shadow = "/images/idea/marker-shadow.png";
				icon.iconSize = new GSize(23, 34);
				icon.shadowSize = new GSize(25, 12);
				icon.iconAnchor = new GPoint(8, 16);
                var marker = new GMarker(new GLatLng(p[1],p[0]),icon);
                map.addOverlay(marker);
                map.setCenter(new GLatLng(p[1],p[0]), 6);

                //change google maps copyright position
				$("#map span").remove();
			} else {
				$(".map").remove();

			}
         });
   		}
	}
}

/**
	@class
	@description First Time User message
*/
REFRESH_APP.firstTimeUserMessage = {

	init: function() {
		//show message only for first time users
		if(!REFRESH_APP.firstTimeUserMessage.isFirstTime()) {
			$("a.hide-this-message").live("click",function(e) {
				e.preventDefault();
				REFRESH_APP.firstTimeUserMessage.hideMessage();
			});
			// todo: turn back on when ideas are in the running
			// REFRESH_APP.firstTimeUserMessage.showMessage();
		}
	},
	hideMessage: function() {
		$("#firstTimeUserMessage").fadeOut();
		REFRESH_APP.firstTimeUserMessage.setCookie();
	},
	showMessage: function() {
		var output = "";
		output += "<div id='firstTimeUserMessage'>";
		output += "<div class='content'><a class='hide-this-message' href=''>Hide this message</a> First time here? Pepsi is giving away $1,300,000 each month to <strong>fund great ideas</strong>, <a href='/how-it-works'>Learn more</a>.<br/>Make sure to check out some of the other <a href='http://www.refresheverything.com/'>" + $("#running-ideas").val() + " ideas</a> competing.";
		output += "</div>";

		$("#header").prepend(output);
	},
	isFirstTime: function() {
		var isFirstTime = REFRESH_APP.firstTimeUserMessage.readCookie();

		if(isFirstTime == null) {
			return false;
		} else {
			return true;
		}
	},
	setCookie: function() {
		$.cookie("PEPSI_USER_MESSAGE", 'false');
	},
	readCookie: function() {
		var showUserMessage =  $.cookie("PEPSI_USER_MESSAGE");
		return showUserMessage;
	}
};

/**
	@class
	@description Vote Button
*/
REFRESH_APP.vote = {
	/**
		Apply click/over/out event to vote button
	*/
	init: function() {
		if(!$("#badge").hasClass("finalist") && !$("#badge").hasClass("grant-awardee")) {



		//init thank you message after 10 votes
		REFRESH_APP.vote.initThanks();

		//check idea state
		REFRESH_APP.vote.getIdeasState();

		this.initDisabled();
		var self = this;
		$('a.idea-button').live('click',self.ideaVote);
		$('a.idea-button').live('mousedown',function() {
			var obj = $(this);
			var parent = obj.parent();
			if(parent.hasClass('idea-disabled')) return;
			obj.addClass('idea-button-down');
		});
		$('a.idea-button').live('mouseup',function() {
			var obj = $(this);
			var parent = $(this).parent();
			if(parent.hasClass('idea-disabled')) return;
			obj.addClass('idea-button-down');
		});
		$('a.idea-button').live('mouseout',function() {
			var obj = $(this);
			obj.removeClass('idea-button-down');
		});

		$('.arrow').ifixpng();

		}
	},
	/**
		Show success message
	*/
	showVoteMsg: function(parent) {
		var msgs = this.voteMessages;
		var msg = msgs[Math.floor(Math.random()*msgs.length)];
		if(msg.length > 10) {
			$("#thanks h2").css({"paddingTop":"10px"});
		}
		$("#thanks h2").text(msg);
		$('.arrow').ifixpng();
		$(".grant-amount, .idea-button").remove();

		REFRESH_APP.vote.switchContainerElements();
	},
	/**
		After user voted switch ranking with sharing div container
	*/
	switchContainerElements: function() {
		
		$("#thanks, #vote-main .thanks").slideDown("fast");

		//$("#sidebar-right .ranking,#sidebar-right .voting-ends, #sidebar-right .facebook-widget").fadeOut();

		$("#sidebar-right .ranking,#sidebar-right .voting-ends,#sidebar-right .facebook-widget, #sidebar-right .idea-text2vote").fadeOut("slow", function() {
			$("#sidebar-right .facebook-widget").after($("#sidebar-right .idea-text2vote"), $("#sidebar-right .ranking"),$("#sidebar-right .voting-ends"));
			$("#sidebar-right .ranking,#sidebar-right .voting-ends, #sidebar-right .facebook-widget, #sidebar-right .idea-text2vote").fadeIn();
		});

		$(".grant-amount, .idea-button").remove();
		
		REFRESH_APP.bitly.init();
		REFRESH_APP.leftSideBar.init();
		
	},

	/**
		Apply mouseover/out event to all disabled ideas.  Shows a black bubble
	*/
	initDisabled: function() {

		$('div.idea-disabled .idea-button').live('mouseover',function(e) {

			var obj = $(this);
			var parent = obj.parent();
			var novote = $('div.idea-no-vote',parent);

			if( novote.length == 0 ) {
				novote = $('<div class="idea-no-vote">You\'ve reached the daily limit of 10 votes.<br /><br />Come back tomorrow. You can vote every day.<br /></div>');
				parent.append(novote);
				novote.show();
			} else {
				novote.show();
			}

		});
		$('div.idea-disabled .idea-button').live('mouseout',function(e) {

			var obj = $(this);
			var parent = obj.parent();
			var novote = $('div.idea-no-vote',parent);
			if( novote.length > 0 ) novote.hide();
		});
	},
	/**
		Vote onload callback.
	*/
	onloadVote: function(json,parent) {

		/*
			{"status":"OK","data":{"leftVotesForToday":4}}
			{"status":"ERROR","errorCode":201,"errorMsg":"User voted for this idea today"}
			{"status":"ERROR","errorCode":202,"errorMsg":"User exceeded daily number of votes"}
			{"status":"ERROR","errorCode":203,"errorMsg":"Not logged"}
			{"status":"ERROR","errorCode":200,"errorMsg":"Idea not valid for voting"}
		*/

		if(!parent.hasClass('idea-voting')) return;
		parent.removeClass('idea-voting');

		if(json.status === 'OK') {

			Vote_Click();

			this.showVoteMsg(parent);
			var numVotes = json.data.leftVotesForToday;
			if(numVotes == 0) REFRESH_APP.vote.disableVote();
			REFRESH_APP.statusBar.updateCounter(numVotes);
			if(numVotes == 0) this.disableVote();
            else REFRESH_APP.signUpPop.check();

			//tracking
			pageTracker._trackEvent('User Submission', 'user vote', parent.find(".idea-button").attr('rel'));
			
			//spotlight tracking
			var axel = Math.random() + "";
			var a = axel * 1000000000000000000;
			document.url = location.href;
			var doPing = new Image();

			// the URL below is a spotlight tag for page1
			doPing.src = REFRESH_APP.general.protocol + "ad.doubleclick.net/activity;src=2155040;type=2010s621;cat=prgvo125;ord="+ a + "?";

		}

		if(json.status === 'ERROR') {

			if(json.errorCode === 201) {
				this.showVoteMsg( parent );
				return;
			}
			if(json.errorCode === 202) {
				parent.addClass('idea-disabled');
				this.disableVote();
				return;
			}
			if(json.errorCode === 203) {
				$("#vote").addClass('idea-enabled').removeClass('idea-voting');
				REFRESH_APP.login.ajaxInit();
				pageTracker._trackEvent('Account', 'login step load - lightbox from vote');
				return;
			}

			parent.append('<span class="idea-error">Sorry. There was<br /> a connection issue.<br /></span>').addClass('idea-enabled');

		}
	},
	/**
		Onload call of the status controller.  Remove 'idea-notloaded' class and set to 'idea-notyetenabled'.  Change class of each
		idea returned status.  If sent ID not returned, enable idea (remove 'idea-notyetenabled' and set class to 'idea-notyetenabled').
		If no votes left, disable all enabled ideas.
		Remove show more button
	*/
	onloadIdeasState: function(data,ids,votes) {
			if(data[ids] === 1) {
				REFRESH_APP.vote.switchContainerElements();
				// already voted
				$('#vote').removeClass("idea-enabled").addClass('idea-disabled');
				$("#vote-button").remove();

				//remove botton vote button
				$("#vote-main .idea-button").remove();
				$("#thanks, #vote-main .thanks").slideDown("fast");
				REFRESH_APP.bitly.init();
			} else if(data[ids] === -1) {
				// don't show vote button, id invalid
			} else if(data[ids] === 0) {
			 	// did not vote yet
				$('#vote').addClass('idea-enabled');
				$(".idea-button").css("display","block");
			}




		if(votes === 0) {
			//set top vote button disabled
			$('#vote').removeClass("idea-enabled").addClass('idea-disabled');
			$(".idea-button").css("display","block");

			//remove botton vote button
			$("#vote-main .idea-button").remove();
			$("#vote-main .thanks").slideDown("fast");
		}

		},
	/**
		Get ideas state.  Send all idea ids with class 'idea-notloaded' to the status controller
	*/
	getIdeasState: function() {

		var ids = '';

		ids = $("#vote-button").attr("rel");

		$.ajax({
			url: '/index/ajaxideasvoted',
			type: "POST",
			data: {ids:ids},
			dataType: "json",
			success: function(json){
				if(json.status === 'OK') {
					REFRESH_APP.statusBar.setCounter(json.leftVotesForToday);
					REFRESH_APP.vote.onloadIdeasState(json.data,ids,json.leftVotesForToday);
				}
				if(json.status === 'ERROR') {
					// if not logged, enable all ideas
					$('#vote').addClass('idea-enabled');
					$(".idea-button").css("display","block");

				}
			},
			error: function() {
				// if ajax error, enable all ideas
				$('div.idea-notloaded').removeClass('idea-notloaded').addClass('idea-enabled');

			}
		});
	},
	/**
		Start the sidebar video
	*/
	disableVote: function() {
		this.showThanks();
		$('.idea-enabled').removeClass('idea-enabled').addClass('idea-disabled');
	},
	/**
		Show thank you popup
	*/
	showThanks: function() {

		if($('thankyou').length > 0) return;

		$.fn.colorbox({
			href:'/index/ajaxthankyou',
			scrolling:false,
			open:true,
			speed:300
		});

	},
	/**
		Vote sucess messages
	*/
	voteMessages: ['Thanks for Voting!','Sweet!','Oh yeah!','Awesome!','Cool!','Gracias!','Alright!','Right on!','Boom!','That\'s right!','Nice one!','Yeah baby!','Love it!','Rock on!','For sure!','Good job!','Bueno!','Muy Bien!'],

	/**
		Idea vote button click event
	*/
	ideaVote: function(e) {
		e.preventDefault();
		if(typeof e.button === 'undefined') return;

		//remove error message
		$(".idea-error").remove();

		var id = this.id;
		var href = this.href;
		var obj = $(this);
		var parent = obj.parent();

		if(parent.hasClass('idea-enabled')) {
			parent.removeClass('idea-enabled').addClass('idea-voting');
			$.ajax({
				url: href,
				type: "POST",
				data: { ok:true },
				dataType: "json",
				success: function(json){

					REFRESH_APP.vote.onloadVote(json,parent);
				},
				error: function() {
					parent.append('<span class="idea-error">Sorry. There was<br /> a connection issue.<br /></span>').removeClass('idea-voting').addClass('idea-enabled');
				}
			});
		}
	},

	/**
		Apply click event share links of the thank you popup
		Apply close click event to "No, thanks" link of the thank you popup
	*/
	initThanks: function() {

		$('p.thankyou-share a').live('click',function(e) {

			e.preventDefault();

			var obj = $(this);
			var parent = $(this).parents('.idea');

			var title = encodeURIComponent( 'Pepsi is giving away millions each month to fund refreshing ideas that change the world. #pepsirefresh @Pepsi' );
			var href = 'http://refresheverything.com';

			if(obj.hasClass('idea-facebook')) {
				title = "Pepsi Refresh Everything";
				var win = 'http://www.facebook.com/sharer.php?u='+href+'&t='+title;
				window.open(win,'facebook-share','toolbar=0,status=0,width=626,height=436');
			}

			if(obj.hasClass('idea-twitter')) {
				var win = 'http://twitter.com/home?status='+title+' + '+href;
				window.open(win,'twitter-share');
			}

		});

		$('a.no-thanks').live('click',function(e) {
			e.preventDefault();
			$.fn.colorbox.close();
		});

	}
}



/**
	@class
	@description More third parties
*/
REFRESH_APP.morebox = {

	initialized: false,
	active: false,
	$morebox: false,
	timeout: false,
	preventClose: false,

	/**
		Init
	*/
	init: function() {
		this.initLink();
	},

	/**
		Init
	*/
	initLink: function() {
		var $moreLink = $('.more-button');
		$moreLink.click( function(e) {
			e.preventDefault();
		});

		$("#more-button-header").mouseover( function(e) {
			e.stopPropagation();

			clearTimeout(REFRESH_APP.morebox.timeout);
			if ( !REFRESH_APP.morebox.initialized ) {
				REFRESH_APP.morebox.initialized = true;
				REFRESH_APP.morebox.initBox($(this));
			} else {
				$('div.' + $(this).attr("id")).addClass("activeMoreBox");
				REFRESH_APP.morebox.$morebox = $('div.' + $(this).attr("id"));
				REFRESH_APP.morebox.$morebox.fadeIn();
			}
		});

		$("#more-button-idea1").mouseover( function(e) {
			e.stopPropagation();

			clearTimeout(REFRESH_APP.morebox.timeout);
			if ( !REFRESH_APP.morebox.initialized ) {
				REFRESH_APP.morebox.initialized = true;
				REFRESH_APP.morebox.initBox($(this));
			} else {
				$('div.' + $(this).attr("id")).addClass("activeMoreBox");
				REFRESH_APP.morebox.$morebox = $('div.' + $(this).attr("id"));
				REFRESH_APP.morebox.$morebox.fadeIn();
			}
		});

		$("#more-button-idea2").mouseover( function(e) {
			e.stopPropagation();

			clearTimeout(REFRESH_APP.morebox.timeout);
			if ( !REFRESH_APP.morebox.initialized ) {
				REFRESH_APP.morebox.initialized = true;
				REFRESH_APP.morebox.initBox($(this));
			} else {
				$('div.' + $(this).attr("id")).addClass("activeMoreBox");
				REFRESH_APP.morebox.$morebox = $('div.' + $(this).attr("id"));
				REFRESH_APP.morebox.$morebox.fadeIn();
			}
		});
	},

	/**
		Init
	*/
	initBox: function(obj) {
		REFRESH_APP.morebox.$morebox = $('div.' + obj.attr("id"));
		REFRESH_APP.morebox.$morebox.fadeIn();
		REFRESH_APP.morebox.$morebox.mouseover( function(e) {
			e.stopPropagation();
			clearTimeout(REFRESH_APP.morebox.timeout);
		});
		REFRESH_APP.morebox.initBody();
	},

	/**
		Init
	*/
	initBody: function() {
		$('body').mouseover( function(e) {
			var id = e.target.id;
			clearTimeout(REFRESH_APP.morebox.timeout);
			REFRESH_APP.morebox.timeout = setTimeout(REFRESH_APP.morebox.close, 200);
		});
	},

	close: function() {
		clearTimeout(REFRESH_APP.morebox.timeout);
		REFRESH_APP.morebox.$morebox.fadeOut();
		$('div.activeMoreBox').each(function() {
			$(this).fadeOut().removeClass("activeMoreBox");
		});
	}

};


/**
	@class
	@description Facebook Twitter Share
*/
REFRESH_APP.share = {
	init: function() {
		$("div.promote-idea a").live("click", function(e) {
			e.preventDefault();

			var service = $(this).attr("class");

			switch(service) {
			  	case "facebook":
					if($('.finalist').length > 0){
			  			win = 'http://www.facebook.com/sharer.php?u='+location.href+'&t=A fantastic finalist for ' + $('#monetary-tier').text() + ':' + document.title + 'Pepsi is giving away millions each month to fund great ideas. The ideas with the most votes recieve grants, so vote for your favorites.';
			  		} else {
						win = 'http://www.facebook.com/sharer.php?u='+location.href+'&t='+document.title;
					}
					break;
				case "twitter":
					if($('.finalist').length > 0){
						title = escape('A fantastic finalist for ' +  $('#monetary-tier').text() + ": "  + REFRESH_APP.share.getDocumentTitle());
					} else {
						title = escape('Vote to give this idea ' +  $('#monetary-tier').text() + ": "  + REFRESH_APP.share.getDocumentTitle());
					}
					win = '/index/share#' + title + '||' + location.href;
					break;
				case "delicious":
					win = 'http://delicious.com/save?v=5&noui&jump=close&url='+location.href+'&title='+document.title;
					break;
			  	case "digg":
			  		win = 'http://digg.com/submit?phase=2&url='+location.href+'&title='+document.title;
			  		break;
			  	case "myspace":
			  		win = 'http://www.myspace.com/index.cfm?fuseaction=postto&t='+document.title+'&c=CONTENTS&u='+location.href;
			  		break;
			  	case "mixx":
			  		win = 'http://www.mixx.com/submit?page_url='+location.href;
			  		break;
			  	case "stumbleupon":
			  		win = 'http://www.stumbleupon.com/submit?url='+location.href+'&title='+document.title;
			  		break;
			  	case "reddit":
			  		win = 'http://www.reddit.com/submit?url='+ location.href + '&title='+document.title;
			  		break;
				case "email":
					REFRESH_APP.promoteEmail.ajaxInit(location.href, document.title);
					break;
			  	}

				if(service != "email") {
			  		window.open(win,service,'toolbar=0,status=0,width=550,height=550');
					//tracking
				  	pageTracker._trackEvent('Social', 'share page', service);
			  	}
		});
	},
	email: {
		init: function() {
			this.showForm();
		},
		showForm: function() {
			$.fn.colorbox({
					href:'/email/',
					scrolling:false,
					open:true,
					speed:300,
					onComplete: function() {
						REFRESH_APP.share.email.setValidation();
						REFRESH_APP.captcha.init();
						REFRESH_APP.charCountdown.init('.textarea-help');
					}
			});	
		},
		/**
			Initializes set validation
		*/
		setValidation: function() {
			REFRESH_APP.general.getScript('/js/validation-email.js');
		}
	},
	getDocumentTitle: function() {
		var title = document.title;
		title = title.split("|");
		title = title[0];
		return title;
	}
}

/**
	@class
	@description Share url
*/
REFRESH_APP.shareUrl = {
	init: function() {
		$(".promote-url").focus(function() {

		  if(this.value == this.defaultValue) {
		  	//copy to clipboard
		  	this.select();
		  }
		});
	}
}



/**
	@class
	@description Gallery
*/
REFRESH_APP.gallery = {
	/**
		Initializes homepage
	*/
	init: function() {
		var category = $("span.category-name").text();

		$("a.view-all-videos-photos").live("click",function(e) {
			e.preventDefault();
			pageTracker._trackEvent('Photo','view gallery',category);
			$("a.back-to-gallery").fadeIn();
			REFRESH_APP.gallery.seeAll();
			$(this).fadeOut();
		});

		$("a.back-to-gallery").live("click", function(e) {
			e.preventDefault();
			REFRESH_APP.gallery.showGallery();
			$("a.view-all-videos-photos").fadeIn();
			$(this).fadeOut();
		});

		//init video
		var url = REFRESH_APP.gallery.getVideoUrl();

		if(url) {
			this.showVideo(url);
			this.showVideoThumb(url);
		} else {
			//show first image
			REFRESH_APP.gallery.showFirstImage();

		}

		$("ul.thumb li img").click(function(e) {
			e.preventDefault();
			$("ul.thumb li img.active").removeClass("active");
			$(this).addClass("active");
			//var url = $(this).attr("rel");
			var imageNr = $(this).attr("rel");

			pageTracker._trackEvent('Photo','view photo',category)

			//check if its a video or image
			if($(this).hasClass("video")) {
				url = REFRESH_APP.gallery.getVideoUrl();
				REFRESH_APP.gallery.showVideo(url);

			} else {
				REFRESH_APP.gallery.showImage(imageNr);
			}
		});
	},
	showFirstImage: function() {
		var firstImage = $("ul.thumb li img").eq(0);
		firstImage.addClass("active");
		var imageNr = firstImage.attr("rel");
		$(".gallery-wrapper img").each(function() {
			if($(this).attr("rel") == imageNr) {
				$(this).addClass("active");
			}
		});
		$(".gallery-wrapper img.active").show();

	},
	getVideoUrl: function() {
		var url = $("ul.thumb li img.video").attr("rel");
		if(url == null) return false;

		if(url.indexOf("watch")) {
			url = url.replace("watch?","");
			url = url.replace("=","/");
		}

		return url;
	},
	showVideoThumb: function(url) {
		var startPosition = url.indexOf("youtube.com/v/");
		var videoId = url.substring(startPosition + 14,url.length);
		var thumbUrl = "http://img.youtube.com/vi/" + videoId + "/2.jpg";
		$("ul.thumb li img.video").attr("src", thumbUrl);
	},
	showImage: function(imageNr) {
			if($("#myytplayer").get(0) != null) {
				$("#myytplayer").remove()
			}

			$(".gallery-wrapper img.active").hide();	
			$(".gallery-wrapper img").removeClass("active");
			$(".gallery-wrapper img").each(function() {
				if($(this).attr("rel") == imageNr) {
					$(this).addClass("active");
				}
			});

			$(".gallery-wrapper img.active").show();

			if($(".gallery-wrapper img.active").length == 0) {
				$(".gallery-wrapper img").each(function() {
					if($(this).attr("rel") == imageNr) {
						$(this).addClass("active");
					}
				});

				$(".gallery-wrapper img.active").show();
			}
	},
	showVideo: function(url) {
		$(".gallery-wrapper img").eq(0).before("<div id='ytapiplayer'>You need Flash player 8+ and JavaScript enabled to view this video.</div>");
		  
	    	var params = { allowScriptAccess: "always", wmode: "transparent" };
	    	var atts = { id: "myytplayer" };

	    	swfobject.embedSWF(url + "?enablejsapi=1&playerapiid=ytplayer",
	                       "ytapiplayer", "425", "356", "8", null, null, params, atts);

	        $(".gallery-wrapper").show();
	},
	seeAll: function() {
		$("div.gallery").fadeOut("slow", function() {
			$("div.gallery-detail").fadeIn("slow", function() {
				$('div.inner-content,#sidebar-left,#sidebar-right').equalHeight();
			});
		});
	},
	showGallery: function() {
		$("div.gallery-detail").fadeOut("slow", function() {
			$("div.gallery").fadeIn("slow", function() {
				$('div.inner-content,#sidebar-left,#sidebar-right').equalHeight();
				$('html, body').animate({scrollTop:400}, 'fast');
			});

		});
	}
};


/**
	@class
	@description New Post / New Image / New Video
*/
REFRESH_APP.post = {
	counter:0,
	
	init: function() {
		$('#learn-more-container').show().addClass("show");
		var ideaId = $("#ideaId").val();
		
		$("#blog-posts a.edit").live("click", function(e) {
			
			e.preventDefault();
			var id = REFRESH_APP.post.counter++;
			var obj = $(this);
			var currentBlogPost = obj.closest("div.post");  
			var postId = $('.id',  currentBlogPost).val(); 
				
			$(".post-admin-loader", currentBlogPost).show();
			$.ajax({
				type: 'POST',
				url: "/ideadetails/edit",
				data: "postId=" + postId + "&ideaId=" + ideaId, 
				success: function(data) {
					$(obj).parent().after('<div style="display:none;" id="form-' + id + '" class="form-edit"></div>');
					$("#form-"+id).slideDown();
					$(".post-admin", "#form-"+id).hide();
					REFRESH_APP.post.createForm(id,data);
					$(".post-admin-loader").hide();
				},
				error: function() {
					$(".post-admin-loader").hide();
				}
			});	
		});
		
		var ideaId = $("#ideaId").val();
		//alert(ideaId);
		$.ajax({
			type: 'POST',
			url: "/ideadetails/postform",
			data: "ideaId=" + ideaId, 
			success: function(data) {
				//alert(data);	
				
				REFRESH_APP.post.createForm('default',data);
			
			}
		});	
	},
	createForm: function(id, data) {
		var obj = '';
		if(id == "default") {
			obj = $('#form-default');
		} else {
			obj = $('#form-'+id);
			
			//edit form cancel cancel
			$("a.cancel", parent).live("click", function(e) {
				e.preventDefault();
				$(".form-edit").fadeOut().remove();
				$(".post-admin").show();
			});
				
		}
		obj.html(data);	
		
		var i = 0;
		REFRESH_APP.post.tabs.init();
		obj.find("form").each(function(i) {
			var formType = $(this).attr("class");
			if(formType == "post") {
				REFRESH_APP.post.tabs.newPost.init($(this));
			} else if(formType == "image") {
				REFRESH_APP.post.tabs.newImage.init($(this));
			} else if(formType == "video") {
				REFRESH_APP.post.tabs.newVideo.init($(this));
			} else {
				return;
			}
			
		});
	},
	tabs: {
		init: function() {
			
			$("ul.tabs").tabs("div.panes > div");
			
		},
		newPost: {
			init: function(parent) {
				var tabs = $("ul.tabs").tabs();
				this.tinyMce(parent);
				
				parent.submit(function(e) {
					e.preventDefault();
					var error = REFRESH_APP.post.tabs.newPost.validateForm(parent);
					if(!error) {
						REFRESH_APP.post.tabs.newPost.submitForm(parent);
					}
				});
				
				//reset form fields
				$("a.cancel", parent).live("click", function(e) {
					e.preventDefault();
					REFRESH_APP.post.tabs.newPost.resetFields();
				});
				
				$("a.trigger-image-tab", parent).live("click", function(e) {
					e.preventDefault();
					tabs.click(1);
					
				});
				
				//trigger video  tab
				$("a.trigger-video-tab", parent).live("click", function(e) {
					e.preventDefault();
					tabs.click(2);
				});
			},
			tinyMce: function(parent) {
				$('textarea.tinyMCE', parent).tinymce({
					script_url : '/js/library/tiny_mce/tiny_mce.js',
					theme : "advanced",
					plugins : "safari,spellchecker,paste",
					theme_advanced_buttons1: "bold,italic,|,bullist,numlist,|,link",
					theme_advanced_buttons2: "",
					theme_advanced_toolbar_location : "top",
					theme_advanced_toolbar_align : "left",
					valid_elements : "a[href|target=_blank],strong/b,i/em,br,p,ol,ul,li",
					force_br_newlines: true
				});
			},
			validateForm: function(parent) {
				var title = $('.post-title', parent).val();
				var caption = $('.post-caption', parent).val();
				var error = false;
				
				//remove all error messages
				$("p.error", parent).remove();
				
				if(title == "") {
					$('.post-title', parent).after('<p style="display:block;margin-top:0;" htmlfor="post-title" generated="true" class="error post-title-error">Please give your post a title.</p>');
					error = true;
				}
				
				if(title.length > 160) {
					$('.post-title', parent).after('<p style="display:block;margin-top:0;" htmlfor="post-title" generated="true" class="error post-title-error">Post title is too long.</p>');
					error = true;
					
				}
				
				if(caption == "") {
					$('.mceEditor', parent).after('<p style="display:block;margin-top:0;" htmlfor="post-caption" generated="true" class="error post-caption-error">You haven’t written a post yet.</p>');
					error = true;
				}
				
				if(caption.length > 5000) {
					$('.mceEditor', parent).after('<p style="display:block;margin-top:0;" htmlfor="post-caption" generated="true" class="error post-caption-error">Post is too long.</p>');
					error = true;
				}
				
				return error;
			},
			submitForm: function(parent) {

				var title = $('.post-title', parent).val();
				var caption = $('.post-caption', parent).val();
				var ideaId = $("#ideaId").val();
				var postId = $('.id', parent).val();

				$(".submit-loader", parent).show();				
				if(!postId) {
					$.post("/ideadetails/addnew", { title: title, caption: caption, ideaId: ideaId, submitType: 'post' },
					function(data){
					  $("p.add", parent).show();
					  $("p.add", parent).fadeOut(5000);
					  REFRESH_APP.blogPosts.init();
					  REFRESH_APP.post.tabs.newPost.resetFields(parent);
					  $(".submit-loader", parent).hide();
					});
				}
				else {
					$.post("/ideadetails/edititem", { postId: postId, title: title, caption: caption, ideaId: ideaId },
					function(data){
					  $("p.add", parent).show();
					  $("p.add", parent).fadeOut(5000);
					  REFRESH_APP.blogPosts.init();
					  $(".submit-loader", parent).hide();
					});
				}		
			},
			resetFields: function(parent) {
				$('.post-title', parent).val('');
				$('.post-caption', parent).val('');
			}
		}, //end newPost
		newVideo: {
			parentForm: null,
			init: function(parent) {
				parentForm = parent;
				var timeout = undefined;
				
				parent.submit(function(e) {
					e.preventDefault();
					
					var error = REFRESH_APP.post.tabs.newVideo.validateForm(parent);
					if(!error) {
						REFRESH_APP.post.tabs.newVideo.submitForm(parent);
					}
				});
				
				//reset form fields
				$("a.cancel", parent).live("click", function(e) {
					e.preventDefault();
					REFRESH_APP.post.tabs.newVideo.resetFields();
				});
				
				$(".video-url", parent).keyup(function() {
					$(".video-url-error", parent).remove();
					if(timeout != undefined) {
						clearTimeout(timeout);
					}
			 		
					timeout = setTimeout(function() {
						timeout = undefined;
						
						var url = $(".video-url", parent).val();
						
						if(url == "") {
							$(".video-url-error", parent).remove();
							$(".video-preview", parent).hide();
							$(".video-title", parent).val('');
							$(".video-caption", parent).val('');
				
							return false;
						}
						
						if(url.length > 10 && REFRESH_APP.post.tabs.newVideo.isValidVideoUrl(url)) {
							REFRESH_APP.post.tabs.newVideo.showVideo(url, parent);
						} else {
							$(".video-url-error", parent).remove();
							$(".video-url", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-title" generated="true" class="error video-url-error">We didn’t recognize that YouTube URL. Please try again.</p>');
						}
				 	}, 500);
				});	
								
				$(".video-title", parent).live("blur", function() {
					if($(this).val() != "") {
						$(".video-title-error", parent).remove();
					}
				});

				$(".video-caption", parent).live("blur", function() {
					if($(this).val() != "") {
						$(".video-caption-error", parent).remove();
					}
				});
				
				$("a.cancel", parent).live("click", function(e) {
					e.preventDefault();
					REFRESH_APP.post.tabs.newVideo.resetFormValues(parent);
				});
			},
			resetFormValues: function(parent) {
				$(".video-preview", parent).hide();
				$("p.error", parent).remove();
				$(".video-title", parent).val('');
				$(".video-url", parent).val('');
				$(".video-caption",parent).val('');
			},
			validateForm: function(parent) {
				var title = $(".video-title", parent).val();
				var url = $(".video-url", parent).val();
				var caption = $(".video-caption",parent).val();
				var error = false;
				
				//remove all error messages
				$("p.error", parent).remove();
				
				if(title == "") {
					$(".video-title", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-title" generated="true" class="error video-title-error">Please let us know what the video is called.</p>');
					error = true;
				}
				
				if(title.length > 160) {
					$(".video-title", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-title" generated="true" class="error video-title-error">Video title is too long.</p>');
					error = true;
				}
					
				// video caption is optional field
				
				if(caption != "" && caption > 300) {
					$(".video-caption", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-title" generated="true" class="error video-caption-error">Video caption is too long</p>');
					error = true;
				}
				
				
				url = REFRESH_APP.post.tabs.newVideo.isValidVideoUrl(url);
				
				if(url == null || url == false) {
					$(".video-url", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-title" generated="true" class="error video-url-error">We didn’t recognize that YouTube URL. Please try again.</p>');
					error = true;
				}
				
				return error;
			},	
			submitForm: function(parent) {

				var url = $('.video-url', parent).val();
				url = REFRESH_APP.post.tabs.newVideo.formatVideoUrl(url);
				var title = $('.video-title', parent).val();
				var caption = $('.video-caption', parent).val();
				var ideaId = $("#ideaId").val();
				var postId = $('.id', parent).val();
				
				$(".submit-loader", parent).show();
				if(!postId) {			
					$.post("/ideadetails/addnew", { url: url, title: title, caption: caption, ideaId: ideaId, submitType: 'video' },
					function(data){
					  $("p.add", parent).show();
					  $("p.add", parent).fadeOut(5000);
					  REFRESH_APP.blogPosts.init();
					  $(".submit-loader", parent).hide();
					  REFRESH_APP.post.tabs.newVideo.resetFields();
					  $(".video-preview", parent).hide();
					});
					
				}
				else {					
					$.post("/ideadetails/edititem", { postId: postId, url: url, title: title, caption: caption, ideaId: ideaId },
					function(data){
					  $("p.add", parent).show();
					  $("p.add", parent).fadeOut(5000);
					  REFRESH_APP.blogPosts.init();
					  $(".submit-loader", parent).hide();
					  REFRESH_APP.post.tabs.newVideo.resetFields();
					  $(".video-preview", parent).hide();
					});
				}
			},
			resetFields: function(parent) {
				$('.video-url', parent).val('');
				$('.video-title', parent).val('');
				$('.video-caption', parent).val('');
			},
			isValidVideoUrl: function(url) {
				
				//remove whitespace
				var url = url.split(' ').join('');
				
				var regexp= /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/
				var isValidUrl = regexp.test(url);
		
				if(isValidUrl) {
					return url;
				} else {
					return false;
				}	
			},
			formatVideoUrl: function(url) {
				if(url.indexOf("watch")) {
					url = url.replace("watch?","");
					url = url.replace("=","/");
				} 
				
				return url;				
			},
			showVideo: function(url, parent) {
				
				if(url == "") return;
				//$(".error").remove();
				
				//reset values
				$(".video-preview", parent).hide();
				$(".video-title", parent).val('');
				$(".video-caption", parent).val('');
				
				
				var videoUrl = REFRESH_APP.post.tabs.newVideo.formatVideoUrl(url);
				
				$(".video-preview", parent).html("<div id='ytapiplayer'>You need Flash player 8+ and JavaScript enabled to view this video.</div>");
				
		    	var params = { allowScriptAccess: "always", wmode: "transparent" };
		    	var atts = { id: "myytplayer1" };
		    	swfobject.embedSWF(videoUrl + "?enablejsapi=1&playerapiid=ytplayer", 
		              "ytapiplayer", "425", "356", "8", null, null, params, atts);

		    	$(".video-preview", parent).show();
		    	
		    			    
		    	//get video parameters
		    	REFRESH_APP.post.tabs.newVideo.getVideoMetaData(url);
			},
			/**
			Get YouTube MetaData
			*/	
			getVideoMetaData: function(url, parent) {
				var codeMatch = url.match("[\\?&]v=([^&#]*)");
				var v_id = (codeMatch) ? codeMatch[1] : '';
				
				var url = 'http://gdata.youtube.com/feeds/videos?vq=' + 
						v_id + 
						'&max-results=1' + 
						'&alt=json-in-script' + 
						'&callback=REFRESH_APP.post.tabs.newVideo.showVideoMetaData' +
						'&orderby=relevance' + 
						'&sortorder=descending' +
						'&format=5';
			
				// Create a JavaScript element that returns our JSON data
				var script = document.createElement('script');
				script.setAttribute('id', 'jsonScript');
				script.setAttribute('type', 'text/javascript');    
				script.setAttribute('src', url);
				document.documentElement.firstChild.appendChild(script);
			},
			showVideoMetaData: function(data) {
				var parent = REFRESH_APP.post.tabs.newVideo.parentForm;
				if (data.feed.entry) {
					var entry = data.feed.entry[0];
					var title = entry.title.$t;
					var $html = $( entry.content.$t );
					
					// Extract description
					var td = $html.find('td')[1]; 
					var description = $(td).find('div:last span').html();
					$(".video-title", parent).val(title);
					$(".video-caption", parent).val(description);
				}
			}
		}, //end newVideo		
		newImage: {
			init: function(parent) {
				var timeout = undefined;
				
				//do nothing if return or arrow keys
				$(".image-url", parent).bind("keypress", function(e) {
             		if (e.keyCode == 13 || e.keyCode == 39 || e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 40) {
						return false;
					} 
         		});
         		
				//reset form fields
				$("a.cancel", parent).live("click", function(e) {
					e.preventDefault();
					REFRESH_APP.post.tabs.newImage.resetFields();
				});
         
				$(".image-url", parent).keyup(function(e) {
					$(".image-url-error", parent).remove();
					
					//set delay after releasing keyup
					if(timeout != undefined) {
						clearTimeout(timeout);
					}
					
					var inputForm = $(this);
				      
					timeout = setTimeout(function() {
						timeout = undefined;
						
						var url = $(".image-url", parent).val();
						$("p.error", parent).remove();
						
						if(url == "") {
							$(".image-url-error", parent).remove();
							$(".image-preview .navigation", parent).hide();
							$(".image-preview", parent).hide();
							$(".image-title", parent).val('');
							$(".image-caption", parent).val('');
							
							return false;
						}
						
						var isValidUrl = REFRESH_APP.post.tabs.newImage.isValidImageUrl(url);
						
						//check if url contains html tags. if true set isValidUrl to true so we can extract the img src
						if(isValidUrl == false) {
							var urlContainsHtmlTags = REFRESH_APP.post.tabs.newImage.urlContainsHtmlTags(url);
							if(urlContainsHtmlTags) {
								isValidUrl = true;
							}
						}
						
						/* check if edit form and new post form is open at the same time. if thats the case we need to make sure the 
						correct context parent element is set */
						if($(".form-edit").length != 0) {
							parent = inputForm.closest("form");
							parent = parent.closest("div");
						}
						
						if(url.length > 10 && isValidUrl) {
							$(".image-preview", parent).hide();
							$(".image-title", parent).val('');
							$(".image-caption", parent).val('');
							var imageType = REFRESH_APP.post.tabs.newImage.getImageType(url, parent);
							
							switch(imageType) {
								case "genericWebsiteUrl": REFRESH_APP.post.tabs.newImage.parseGenericWebsiteUrl.init(url, parent); break;
								case "flickr": REFRESH_APP.post.tabs.newImage.parseFlickrUrl.init(url, parent); break;
								case "youtube": REFRESH_APP.post.tabs.newImage.parseYouTubeUrl.init(url, parent); break;
								case "image": REFRESH_APP.post.tabs.newImage.parseGenericImage.init(url, parent); break;
								case "imageWithHtml": REFRESH_APP.post.tabs.newImage.parseImageWithHtml.init(url, parent); break;
								default: return;
							}
						} else {
							$(".image-url-error", parent).remove();
							$(".image-url", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-caption" generated="true" class="error image-url-error">We didn’t recognize that Image Url. Please try again.</p>');
						}
				 	}, 500);
				});

				//init form submit				
				parent.submit(function(e) {
					e.preventDefault();
					
					var error = REFRESH_APP.post.tabs.newImage.validateForm(parent);
					
					if(!error) {
						REFRESH_APP.post.tabs.newImage.submitForm(parent);
					}
				});
			},
			isValidImageUrl: function(url) {
				//remove whitespace
				var url = url.split(' ').join('');
				
				var regexp= /[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/
				var isValidUrl = regexp.test(url);
				
				if(isValidUrl) {
					if(url.indexOf("http://") != -1) {
						url = "http://" + url;
					}
					return url;
				} else {
					return false;
				}
			},
			resizeImagesToThumbnails: function(parent) {
				$(".image-preview img", parent).kepresize({maxWidth: 160});
				$(".image-preview", parent).show();
				$(".image-preview .thumbnails img", parent).show();
			},
			parseGenericImage: {
				init: function(url, parent) {
					
					$(".image-url-loader", parent).show();
					$(".image-preview .thumbnails", parent).html('<img src="' + url + '">');
					
					//save parent and pass it to downloadImages
					$('body').data('parent', parent);

					$(".image-preview", parent).find('img').batchImageLoad({
						loadingCompleteCallback:  REFRESH_APP.post.tabs.newImage.parseGenericWebsiteUrl.downloadImages
					});				
				}
			},
			parseFlickrUrl: {
				init:function(url,parent) {
					this.getImages(url, parent);	
				},
				getImages: function(url, parent) {
				
					if(url == "") return;
					
					regex = "photos/[^/]+/([0-9]+)";
					var photos = url.match(regex);
					
					if(photos != null) {
						var photoid = photos[1];
						
						// get photo info
						$("span.image-url-loader", parent).show();
						$.ajax({
							type: 'GET',
							timeout: 6000,
							url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20flickr.photos.info%20where%20photo_id%3D" + encodeURIComponent(photoid) + "&format=json&callback=?", 
							dataType: 'jsonp',
							success: function(data, textStatus) {
								var src = "http://farm" + data.query.results.photo.farm + ".static.flickr.com/" + data.query.results.photo.server + "/" + data.query.results.photo.id + "_" + data.query.results.photo.secret + ".jpg";
							
								$(".image-preview .thumbnails", parent).html('<img src="' + src + '">');
								$(".image-preview", parent).show();
								$(".image-preview .thumbnails img", parent).show();
								$(".image-preview img", parent).kepresize({maxWidth: 160});
								$(".image-title", parent).val(data.query.results.photo.title);
								$(".image-caption", parent).val(data.query.results.photo.description);
								$(".image-preview .navigation", parent).hide();
								$("span.image-url-loader", parent).hide();
							},
							error: function(objAJAXRequest, strError) {
								$(".image-url", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-caption" generated="true" class="error image-url-error">Sorry, No Images Found.</p>');
							}
						});
					} else {
						//try to get images via the generic parser
						REFRESH_APP.post.tabs.newImage.parseGenericWebsiteUrl.init(url, parent)
					}
				}
			},
			/* parse url and filter out img src */
			parseImageWithHtml: {
				init: function(url, parent) {
					
					//find image tags
					var matches = $(url).find("img");
					var img = "";
					
					$(matches).each(function() {
						img += '<img src="' + $(this).attr("src") + '"/>';
					});
					
					//save parent and pass it to downloadImages
					$('body').data('parent', parent);
					
					//download images and calculate width
					$(".image-preview .thumbnails", parent).html(img);
					$(".image-preview .thumbnails img", parent).batchImageLoad({
						loadingCompleteCallback: REFRESH_APP.post.tabs.newImage.parseGenericWebsiteUrl.downloadImages
					});
				}
			},
			parseGenericWebsiteUrl: {
				init: function(url,parent) {
					this.getImages(url,parent);
				},
				getImages: function(url, parent) {
					var inputUrl = url;
					if(url == "") return;
					$("span.image-url-loader", parent).show();
					$.ajax({
						type: 'GET',
						timeout: 6000,
						url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(url) + "%22%20and%0A%20%20%20%20%20%20xpath%3D'%2F%2Fimg'&format=json&callback=?", 
						dataType: 'jsonp',
						success: function(data, textStatus) {
							//console.log(data);
							if(data == undefined || data.query == undefined) {
								$(".image-url", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-caption" generated="true" class="error image-url-error">Sorry, No Images Found.</p>');
								$(".image-url-loader", parent).hide();
								return;
								
							}
							if(data.query.count > 1) {
								
								var img = "";
								for (var i=0; i<data.query.count; i++) {
									var src = data.query.results.img[i].src;
									var url = "";
									
									//if yahoo returns more than 1 base url take the one with the highest number
									var urlArr = '';
									if(data.query.diagnostics != undefined) {
										urlArr = data.query.diagnostics.url.length;

									}
									
									var width = data.query.results.img[i].width;
									
									if(urlArr > 0 && urlArr) {
										url = data.query.diagnostics.url[urlArr-1].content
									} else if(urlArr == undefined) {
										url = data.query.diagnostics.url.content;
									} else {
										url = inputUrl;
									}
									
									if(src != undefined) {
										//if image src has relative path then build url manually
										if(src.indexOf("http://") == -1) { 
											var src = REFRESH_APP.post.tabs.newImage.parseGenericWebsiteUrl.formatImageSrcPath(src, url);
											
											//if we can get the image width from yahoo we don't need to download the image first to calculate image width
											if(width == undefined) {
												img += "<img class='download-image' rel='" + url + "' id='img_" + i + "' src='" + src + "' alt=''/>";
											} else {
												
												img += "<img width='" + width + "' rel='" + url + "' id='img_" + i + "' src='" + src + "' alt=''/>";
											}
										} else {
											//if we can get the image width from yahoo we don't need to download the image first to calculate image width
											if(width == undefined) {
												img += "<img class='download-image' rel='" + url + "' id='img_" + i + "' src='" + src + "' alt=''/>";
											} else {
												
												img += "<img width='" + width + "' rel='" + url + "' id='img_" + i + "' src='" + src + "' alt=''/>";
											}
										}
									}
									
									
								}

								$(".image-preview .thumbnails", parent).html(img);
								
								//save parent and pass it to downloadImages
								$('body').data('parent', parent);
					
								$(".image-preview .thumbnails img.download-image", parent).batchImageLoad({
									loadingCompleteCallback: REFRESH_APP.post.tabs.newImage.parseGenericWebsiteUrl.downloadImages
								});
								
								REFRESH_APP.post.tabs.newImage.parseGenericWebsiteUrl.setImageDescription(url, parent);
								
							} else {
								$(".image-url", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-caption" generated="true" class="error image-url-error">Sorry, No Images Found.</p>');
								$(".image-url-loader", parent).hide();
							}
						}
					});
					
				}, // END getImages
				downloadImages: function() {
					var parent = $('body').data('parent');
					var error = "";
					$(".image-preview .thumbnails img", parent).each(function() {
						
						var src = $(this).attr("src");
						var width = $(this).attr("width");
						var height = $(this).attr("height");
						
						if(width == "" || height == "") {	
							var image = new Image();
							image.src = src;
							var width = image.width;
							var height = image.height;
						} 
												
						//remove images if width smaller than 140 pixels
						if(height <= 1 || width < 140) {
							$(this).remove();
						} else if(height > 1500 || width > 2000) {
							error = "tooLarge";
						}
					});
					
					var imageCount = $(".image-preview .thumbnails img", parent).length;
					
					if(imageCount == 1) {
						$(".image-preview", parent).show();
						$(".image-preview .navigation", parent).hide();
					} else if(imageCount > 1) {
						$(".image-preview", parent).show();
						$(".image-preview .navigation", parent).show();
						$(".next", parent).addClass("active");	
						REFRESH_APP.post.tabs.newImage.parseGenericWebsiteUrl.initPrevNextArrows(parent);						
					} else {
						$(".image-url", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-caption" generated="true" class="error image-url-error">Sorry, No Images Found.</p>');
						$(".image-title", parent).val('');
						$(".image-caption", parent).val('');
					}
					
					if(error == "") {
						//resize images
						$(".image-preview .thumbnails img", parent).kepresize({maxWidth: 160});
						
						//show first image
						$(".image-preview .thumbnails img", parent).eq(0).show();
								
						//reset counter
						$("span.counter", parent).text(1);
							
						//set total counter
						$("span.counter-total", parent).text(imageCount);
						
						//hide loader
						$(".image-url-loader", parent).hide();
					} else {
						//prevent image from saving as image size is too big. saved in data and validated again in validateForm function
						$("body").data("imageTooLarge","true");
						
						$(".image-url", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-caption" generated="true" class="error image-url-error">Sorry, the Image size is too large.</p>');
						$(".image-preview", parent).hide();
						$(".image-url-loader", parent).hide();					
					}					
				},
				showPreview: function(parent, imageCount) {
				
					//hide arrows if counter equals 1
					if(imageCount == 1) {
						$(".image-preview", parent).show();
						$(".image-preview .navigation", parent).hide();
					} else {
						$(".image-preview", parent).show();
						$(".image-preview .navigation", parent).show();
						$(".next", parent).addClass("active");	
					}
				},
				hidePreview: function(parent) {
					$(".image-preview", parent).show();
					$(".image-preview .navigation", parent).show();
					$(".next", parent).removeClass("active");
					$(".prev", parent).removeClass("active");
				},
				formatImageSrcPath: function(src, url) {
					if(url == "") return;
					var temp = src;
					var intIndexOfMatch = src.indexOf( "../" );
					var i = 0;
					
					//remove '../' from source
					while (intIndexOfMatch != -1){
						src = src.replace( "../", "" )
			  			intIndexOfMatch = src.indexOf( "../" ); 
			  			i++;
			  		}
			  		
			  		src = temp;
			  		//check for "./" paths
			  		if(i == 0) {
			  			intIndexOfMatch = src.indexOf( "./" );
						var i = 0;
					
						//remove '../' from source
						while (intIndexOfMatch != -1){
							src = src.replace( "./", "" )
			  				intIndexOfMatch = src.indexOf( "./" ); 
			  				i++;
			  			}
			  		}
			  		
			  		//remove http://
			  		url = url.replace("http://","");
					url = url.split("/");
					
					var newUrl = "";
					
					if(i > 0) {
						//depending in '../' move level up in image path
						for(k=0;k<=i;k++) {
							newUrl += url[k] + "/";
						}
						
						src = "http://" + newUrl + src;
					} else {
						//no ../ found use url plus src
						src = "http://" + url + "/" + src;
					}
					
					//remove whitespace
					src = src.split(' ').join('');

					return src;

				},
				setImageDescription: function(url, parent) {
					
					if(url == "") return;
					
					//get document meta description
					$.ajax({
						type: 'GET',
						timeout: 6000,
						url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(url) + "%22%20and%20xpath%3D'%2F%2F*%5B%40name%3D%22description%22%5D'&format=json&callback=?",
						dataType: 'jsonp',
						success: function(data, textStatus) {
							
							if(data.query.results != null) {
								$(".image-caption", parent).val(data.query.results.meta.content);
							
							}
						}
					});

					//get document title
					$.ajax({
						type: 'GET',
						timeout: 6000,
						url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(url) + "%22%20and%20xpath%3D'%2F%2Ftitle'&format=json&callback=?",
						dataType: 'jsonp',
						success: function(data, textStatus) {
							if(data.query.results != null) {
								$(".image-title", parent).val(data.query.results.title);
							
							}
						}
					});
				}, // END setImageDescription
				initPrevNextArrows: function(parent) {
					var position = 1;
					
					$(".next", parent).unbind("click");
					$(".next", parent).click( function(e) {
						e.preventDefault();	
						var imageCounter = $(".image-preview .thumbnails img", parent).length;
						if(position >= 1 && position < imageCounter) { 
						    
							$(".image-preview .thumbnails img", parent).eq(position-1).hide();
							position++;
							$("span.counter", parent).text(position);
							$(".image-preview .thumbnails img", parent).eq(position-1).show();
				
							if(position >= 0 && position < imageCounter) { 
								$(".prev", parent).addClass("active");
								$(this).addClass("active"); 
							} else { 	
								$(this).removeClass("active"); 
							}
						}
					});
					//$(".prev". parent).unbind("click");
					$(".prev", parent).click(function(e) {
						e.preventDefault();
						var imageCounter = $(".image-preview .thumbnails img", parent).length;
						if(position > 1) {
							$(".image-preview .thumbnails img", parent).eq(position-1).hide();
							position--;
							$(".image-preview .thumbnails img", parent).eq(position-1).show();
							$("span.counter", parent).text(position);
							if(position == 1) { 
								$(this).removeClass("active");
								$(".next", parent).addClass("active");
							} else {
								$(".next", parent).addClass("active");
								$(this).addClass("active");
							}
						}
					});	
				} // END initPrevNextArrows	
			}, // END parseGenericImageUrl
			urlContainsHtmlTags: function(url) {
				var matchHtmlTags = /<("[^"]*"|'[^']*'|[^'">])*>/gi; 
				var match = url.match(matchHtmlTags);
				
				if(match) {
					return true;
				} else {
					return false;
				}
			},
			getImageType: function(url, parent) {
			
				var urlContainsHtmlTags = REFRESH_APP.post.tabs.newImage.urlContainsHtmlTags(url);
				
				if(urlContainsHtmlTags) {
					return "imageWithHtml";
				}
				
				//convert url to lowercase in case someone uses upper case for extension
				url = url.toLowerCase();

				if(url.indexOf("flickr") != -1) {
					//check if url is full flickr image path
					if(url.indexOf("jpg") != -1 || url.indexOf("png") != -1 || url.indexOf("gif") != -1){
						return "image";
					} else {
						return "flickr";
					}
				} else if(url.indexOf("jpg") != -1 || url.indexOf("png") != -1 || url.indexOf("gif") != -1){
					return "image";
				} else {
					return "genericWebsiteUrl";
				}
			},
			validateForm: function(parent) {
				var title = $(".image-title", parent).val();
				var url = REFRESH_APP.post.tabs.newImage.isValidImageUrl($(".image-url",parent).val());
				var caption = $(".image-caption",parent).val();
				var error = false;
				
				//remove all error messages
				$("p.error", parent).remove();
										
				if(title == "") {
					$(".image-title", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-title" generated="true" class="error image-title-error">Please enter a Image Title.</p>');
					error = true;
				}
				
				if(title.lengt > 160) {
					$(".image-title", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-title" generated="true" class="error image-title-error">Image Title is too long.</p>');
					error = true;
				}
					
				// image caption is optional field
				if(caption != "" && caption.length > 300) {
					$(".image-caption", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-title" generated="true" class="error image-caption-error">Image description is too long.</p>');
					error = true;
					
				}
				
				var imageTooLarge = $("body").data("imageTooLarge");
				if(imageTooLarge == "true") {
					$(".image-url", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-caption" generated="true" class="error image-url-error">Sorry, the Image size is too large.</p>');
					error = true;
				}
				
				if(url == false || url == null) {
					$(".image-url", parent).after('<p style="display:block;margin-top:0;" htmlfor="post-caption" generated="true" class="error image-url-error">We didn\'t recognize that Image Url. Please try again.</p>');
					error = true;
				}
				
				return error;
			},
			submitForm: function(parent) {
				$(".submit-loader", parent).show();
				
				var url = "";
				
				//if more than one thumbnail get the active one
				if($(".thumbnails img", parent).length > 0) {
					var imgIndex = $("span.counter",parent).text();
					url = $(".thumbnails img").eq(imgIndex-1).attr("src");
				} else {
					
					url = $('.image-url', parent).val();
				}
				
				var title = $('.image-title', parent).val();
				var caption = $('.image-caption', parent).val();
				var ideaId = $("#ideaId").val();
				var postId = $('.id', parent).val();
								
				if(!postId) {
					$.post("/ideadetails/addnew", { url: url, title: title, caption: caption, ideaId: ideaId, submitType: 'image' },
					function(data){
					  $("p.add", parent).show();
					  $("p.add", parent).fadeOut(5000);
					  REFRESH_APP.blogPosts.init();
					  REFRESH_APP.post.tabs.newImage.resetFields(parent);
					  $(".submit-loader", parent).hide();
					  $(".image-preview", parent).hide();
					  $("body").data("imageTooLarge","");
					 // REFRESH_APP.tester.init();
					});
				}
				else {
					$.post("/ideadetails/edititem", { postId: postId, url: url, title: title, caption: caption, ideaId: ideaId },
					function(data){
					  $("p.add", parent).show();
					  $("p.add", parent).fadeOut(5000);
					  REFRESH_APP.blogPosts.init();
					  REFRESH_APP.post.tabs.newImage.resetFields(parent);
					  $(".submit-loader", parent).hide();
					  $(".image-preview", parent).hide();
					  $("body").data("imageTooLarge","");
					});
				}
				
				//ajax submit
								//$("#tab-" + action + " .loader").hide();
				
				//if(error == false) {
					//$("#tab-new-post p.confirmation-message").show();
					///$("#tab-new-post p.confirmation-message").fadeOut(5000);
					//REFRESH_APP.newPost.resetPostFormFields();
			},
			resetFields: function(parent) {
				$('.error', parent).remove('');
				$('.image-title', parent).val('');
				$('.image-caption', parent).val('');
				$('.image-url', parent).val('');	
			}
		} //END newImage
	}
}

/**
	@class 
	@description blog posts
*/
REFRESH_APP.blogPosts = {
	init: function(postType, limit) {
		if (postType === undefined) {
            postType = 'all';
        }
        
		if (limit === undefined) {
            limit = 5;
        }
		
		this.getBlogPosts(postType, limit);	
	},
	getBlogPosts: function(postType, limit) {
		var ideaId = $("#ideaId").val();
		
		$(".blog-post-loader").show();
		$.ajax({
			type: 'GET',
			url: "/ideadetails/blogposts",
			data: "ideaId=" + ideaId + "&postType=" + postType + "&limit=" + limit, 
			success: function(data, textStatus) {
				
				$("#blog-posts .blog-posts-content").html(data);
				
				if($("#blog-posts .post").length > 0) {
					$('#learn-more-container').hide().removeClass("show");
				}
				
				$(".posts-loader").remove();
				
				$("#blog-posts .blog-posts-content").hide();
				
				
				$("#blog-posts .post-image").batchImageLoad({
					loadingCompleteCallback: REFRESH_APP.blogPosts.resizeImages
				});	
				
				$(".inner-content").css("min-height","0");
					
				
				$("#blog-posts .post:last").css("border-bottom","none");
				REFRESH_APP.leftSideBar.init();
							
			},
			error: function() {
				$("#blog-posts").html("Could not retrieve blog posts. Please try it again.");
				$(".blog-post-loader").hide();
			}
		});		
	},
	resizeImages: function() {
		$("#blog-posts .post-image").each(function() {
			var image = new Image();
			var src = $(this).attr("src");
			image.src = src;
			
			if(image.width > 520) {
				$("#blog-posts .post-image").css({"width":"520px","height":"auto"});
			}
		});
		
		$("#blog-posts .blog-posts-content").show();
		REFRESH_APP.leftSideBar.setHeight();
		$(".blog-post-loader").hide();
	}
}
/**
	@class 
	@description blog posts
**/
REFRESH_APP.posts = {
	init: function() {
		this.resizeImages();
		this.deletePost.init();
		//this.editPost.init();
	},
	deletePost: {
		init: function() {
			$("#blog-posts a.delete").live("click", function(e) {
				e.preventDefault();
	
				var current_element_id = $(this).attr('id');
				var extract_id_regex = /^delete_post_([0-9]+)$/;
				var matches = extract_id_regex.exec(current_element_id);
				REFRESH_APP.posts.deletePost.postId = matches[1];
				
				
				REFRESH_APP.posts.deletePost.confirmation();
				$(this).parent().find("object").hide();	
			});
		},
		confirmation: function() {
			$.fn.colorbox({
				href:'/ideadetails/deletepopup',
				scrolling:false,
				open:true,
				speed:300,
				onComplete: REFRESH_APP.posts.deletePost.initButtons
			});
		},
		initButtons: function() {			
			$("a.delete-post-yes").click(function(e) {
				e.preventDefault();
				
				var ideaId = $("#ideaId").val();
				var postId = REFRESH_APP.posts.deletePost.postId;
	
				$.post("/ideadetails/deleteitem", { ideaId: ideaId, postId: postId },
				function(data){
				  REFRESH_APP.blogPosts.init();
				  $.fn.colorbox.close();
				});
			
				
			});
			
			$("a.delete-post-no").click(function(e) {
				e.preventDefault();
				$.fn.colorbox.close();
			});
			
		}
	},
	resizeImages: function() {
 		$('#blog-posts .post-image').each(function() {
	        var maxWidth = 540; // Max width for the image
	        var maxHeight = 300;    // Max height for the image
	        var ratio = 0;  // Used for aspect ratio
	        var width = $(this).width();    // Current image width
	        var height = $(this).height();  // Current image height
	 
	        // Check if the current width is larger than the max
	        if(width > maxWidth){
	            ratio = maxWidth / width;   // get ratio for scaling image
	            $(this).css("width", maxWidth); // Set new width
	            $(this).css("height", height * ratio);  // Scale height based on ratio
	            height = height * ratio;    // Reset height to match scaled image
	            width = width * ratio;    // Reset width to match scaled image
	        }
	 
	        // Check if current height is larger than max
	        if(height > maxHeight){
	            ratio = maxHeight / height; // get ratio for scaling image
	            $(this).css("height", maxHeight);   // Set new height
	            $(this).css("width", width * ratio);    // Scale width based on ratio
	            width = width * ratio;    // Reset width to match scaled image
	        }
	        
	        
    	});
	}
}

/**
	@class
	@description Sets rounded corners for items classed 'rounded'
*/
REFRESH_APP.roundedCorners = {
	/**
		Initializes rounded corners
	*/
	init: function() {
		if ($.browser.mozilla) {
			$("img.rounded").each( function () {
				var $img = $(this);
				var $wrapper = $('<div class="rounded"></div>');
				$wrapper.width($img.width());
				$wrapper.height($img.height());
				$wrapper.css({
					'background-image' : 'url('+$img.attr('src')+')',
					'float' : $img.css('float'),
					'margin-right' : $img.css('margin-right'),
					'margin-left' : $img.css('margin-left'),
					'margin-bottom' : $img.css('margin-bottom'),
					'margin-top' : $img.css('margin-top')
				});
				$img.replaceWith($wrapper);
			});
		} else {
			REFRESH_APP.general.getScript('/js/library/dd_roundies.min.js',function() {
				DD_roundies.addRule('.rounded', '10px', true);
				DD_roundies.addRule('.less-rounded', '5px', true);
			});
		}
	}
};

$(document).ready(function(){
	REFRESH_APP.firstTimeUserMessage.init();
	REFRESH_APP.gallery.init();
	REFRESH_APP.vote.init();
	REFRESH_APP.shareUrl.init();
	REFRESH_APP.comments.init();
	REFRESH_APP.morebox.init();
	REFRESH_APP.share.init();
	REFRESH_APP.affiliated.init();
	REFRESH_APP.map.init();
	REFRESH_APP.leftSideBar.init();
	REFRESH_APP.analytics.init();
	REFRESH_APP.post.init();
	REFRESH_APP.blogPosts.init();
	REFRESH_APP.posts.init();
	
	// Implement rounded corners
	REFRESH_APP.roundedCorners.init();
	
	//get bitly value via javascript if its not in db
	if($("#promote-url-sidebar").val() == "") {
    	REFRESH_APP.bitly.init();
    }	
});

$('#filterPosts').live('click', function(e){
	e.preventDefault();
	REFRESH_APP.blogPosts.init();
});
$('#filterVideos').live('click', function(e){
	e.preventDefault();
	REFRESH_APP.blogPosts.init('video');
});
$('#filterImages').live('click', function(e){
	e.preventDefault();
	REFRESH_APP.blogPosts.init('image');
});
$('.load-more').live('click', function(e){
	e.preventDefault();
	$(this).addClass("loading");
	var current_element_id = $(this).attr('id');
	var extract_id_regex = /^([A-Za-z]+)_([0-9]+)$/;
	var matches = extract_id_regex.exec(current_element_id);

	var postType = matches[1];
	var limit = matches[2];

	REFRESH_APP.blogPosts.init(postType, limit);
});

function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById(playerId);
  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
	var category = $("span.category-name").text();
	//track play
	if(newState == 3) {
		pageTracker._trackEvent('Video','play',category);	
	}
}

/*
 * ----------------------
 * - Képátméretező v0.2 -
 * ----------------------
 *
 * Készítette: Burda Roland - 2009 július 10.
 * E-mail: qkac87@gmail.com
 * SZABADON TERJESZTHETŐ, ÉS FELHASZNÁLHATÓ! CSERÉBE, EZT A SZÖVEGET NE TÁVOLÍTSD EL! KÖSZÖNÖM!
 * 
 * Példa a használathoz:
 * ---------------------
 *
 * $(document).ready(function(){
 *     $('.thumb').kepresize({maxWidth:200, maxHeight:150});
 * });
 *
 * VAGY:
 *
 * $(document).ready(function(){
 *     $('.thumb').kepresize();
 * });
 *
 */

(function($){
	
	$.fn.kepresize = function(options){

		var defaults = {  
			maxWidth : 110,  // Max width for the image
			maxHeight : 115  // Max height for the image
		};

		var options = $.extend(defaults, options); 

		return this.each(function() {
			obj = $(this);
			
			// Nulling widht and height
			var width = 0;
			var height = 0;
			
			// Get image parameters, and calculate scale
			var width = obj.width();    // Current image width
			var height = obj.height();  // Current image height
			var x_scale = width / options.maxWidth;   // X scale
			var y_scale = height / options.maxHeight; // Y scale
			
			if(y_scale > x_scale){
				new_height = Math.ceil(height * (1/y_scale));
				new_width = Math.ceil(width * (1/y_scale));
				obj.css("height", new_height);
				obj.css("width", new_width);
			} else {
				new_height = Math.ceil(height * (1/x_scale));
				new_width = Math.ceil(width * (1/x_scale));
				obj.css("height", new_height);
				obj.css("width", new_width);
			}
		});
		
	};
})(jQuery);

	/*
	 * jquery.tools 1.1.2 - The missing UI library for the Web
	 * 
	 * [tools.tabs-1.0.4]
	 * 
	 * Copyright (c) 2009 Tero Piirainen
	 * http://flowplayer.org/tools/
	 *
	 * Dual licensed under MIT and GPL 2+ licenses
	 * http://www.opensource.org/licenses
	 * 
	 * -----
	 * 
	 * File generated: Fri Feb 26 09:01:47 GMT 2010
	 */
	(function(d){d.tools=d.tools||{};d.tools.tabs={version:"1.0.4",conf:{tabs:"a",current:"current",onBeforeClick:null,onClick:null,effect:"default",initialIndex:0,event:"click",api:false,rotate:false},addEffect:function(e,f){c[e]=f}};var c={"default":function(f,e){this.getPanes().hide().eq(f).show();e.call()},fade:function(g,e){var f=this.getConf(),j=f.fadeOutSpeed,h=this.getPanes();if(j){h.fadeOut(j)}else{h.hide()}h.eq(g).fadeIn(f.fadeInSpeed,e)},slide:function(f,e){this.getPanes().slideUp(200);this.getPanes().eq(f).slideDown(400,e)},ajax:function(f,e){this.getPanes().eq(0).load(this.getTabs().eq(f).attr("href"),e)}};var b;d.tools.tabs.addEffect("horizontal",function(f,e){if(!b){b=this.getPanes().eq(0).width()}this.getCurrentPane().animate({width:0},function(){d(this).hide()});this.getPanes().eq(f).animate({width:b},function(){d(this).show();e.call()})});function a(g,h,f){var e=this,j=d(this),i;d.each(f,function(k,l){if(d.isFunction(l)){j.bind(k,l)}});d.extend(this,{click:function(k,n){var o=e.getCurrentPane();var l=g.eq(k);if(typeof k=="string"&&k.replace("#","")){l=g.filter("[href*="+k.replace("#","")+"]");k=Math.max(g.index(l),0)}if(f.rotate){var m=g.length-1;if(k<0){return e.click(m,n)}if(k>m){return e.click(0,n)}}if(!l.length){if(i>=0){return e}k=f.initialIndex;l=g.eq(k)}if(k===i){return e}n=n||d.Event();n.type="onBeforeClick";j.trigger(n,[k]);if(n.isDefaultPrevented()){return}c[f.effect].call(e,k,function(){n.type="onClick";j.trigger(n,[k])});n.type="onStart";j.trigger(n,[k]);if(n.isDefaultPrevented()){return}i=k;g.removeClass(f.current);l.addClass(f.current);return e},getConf:function(){return f},getTabs:function(){return g},getPanes:function(){return h},getCurrentPane:function(){return h.eq(i)},getCurrentTab:function(){return g.eq(i)},getIndex:function(){return i},next:function(){return e.click(i+1)},prev:function(){return e.click(i-1)},bind:function(k,l){j.bind(k,l);return e},onBeforeClick:function(k){return this.bind("onBeforeClick",k)},onClick:function(k){return this.bind("onClick",k)},unbind:function(k){j.unbind(k);return e}});g.each(function(k){d(this).bind(f.event,function(l){e.click(k,l);return false})});if(location.hash){e.click(location.hash)}else{if(f.initialIndex===0||f.initialIndex>0){e.click(f.initialIndex)}}h.find("a[href^=#]").click(function(k){e.click(d(this).attr("href"),k)})}d.fn.tabs=function(i,f){var g=this.eq(typeof f=="number"?f:0).data("tabs");if(g){return g}if(d.isFunction(f)){f={onBeforeClick:f}}var h=d.extend({},d.tools.tabs.conf),e=this.length;f=d.extend(h,f);this.each(function(l){var j=d(this);var k=j.find(f.tabs);if(!k.length){k=j.children()}var m=i.jquery?i:j.children(i);if(!m.length){m=e==1?d(i):j.parent().find(i)}g=new a(k,m,f);j.data("tabs",g)});return f.api?g:this}})(jQuery);


/*
	reflection.js for jQuery v1.03
	(c) 2006-2009 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/
(function(a){a.fn.extend({reflect:function(b){b=a.extend({height:1/3,opacity:0.5},b);return this.unreflect().each(function(){var c=this;if(/^img$/i.test(c.tagName)){function d(){var g=c.width,f=c.height,l,i,m,h,k;i=Math.floor((b.height>1)?Math.min(f,b.height):f*b.height);if(a.browser.msie){l=a("<img />").attr("src",c.src).css({width:g,height:f,marginBottom:i-f,filter:"flipv progid:DXImageTransform.Microsoft.Alpha(opacity="+(b.opacity*100)+", style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy="+(i/f*100)+")"})[0]}else{l=a("<canvas />")[0];if(!l.getContext){return}h=l.getContext("2d");try{a(l).attr({width:g,height:i});h.save();h.translate(0,f-1);h.scale(1,-1);h.drawImage(c,0,0,g,f);h.restore();h.globalCompositeOperation="destination-out";k=h.createLinearGradient(0,0,0,i);k.addColorStop(0,"rgba(255, 255, 255, "+(1-b.opacity)+")");k.addColorStop(1,"rgba(255, 255, 255, 1.0)");h.fillStyle=k;h.rect(0,0,g,i);h.fill()}catch(j){return}}a(l).css({display:"block",border:0});m=a(/^a$/i.test(c.parentNode.tagName)?"<span />":"<div />").insertAfter(c).append([c,l])[0];m.className=c.className;a.data(c,"reflected",m.style.cssText=c.style.cssText);a(m).css({width:g,height:f+i,overflow:"hidden"});c.style.cssText="display: block; border: 0px";c.className="reflected"}if(c.complete){d()}else{a(c).load(d)}}})},unreflect:function(){return this.unbind("load").each(function(){var c=this,b=a.data(this,"reflected"),d;if(b!==undefined){d=c.parentNode;c.className=d.className;c.style.cssText=b;a.removeData(c,"reflected");d.parentNode.replaceChild(c,d)}})}})})(jQuery);

// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
jQuery(function($) {
	$("img.reflect").reflect({/* Put custom options here */});
});

/* IPNGIX */

(function($){$.ifixpng=function(customPixel){$.ifixpng.pixel=customPixel};$.ifixpng.getPixel=function(){return $.ifixpng.pixel||'images/pixel.gif'};var hack={ltie7:$.browser.msie&&$.browser.version<7,filter:function(src){return"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')"}};$.fn.ifixpng=hack.ltie7?function(){return this.each(function(){var $$=$(this);var base=$('base').attr('href');if(base){base=base.replace(/\/[^\/]+$/,'/')}if($$.is('img')||$$.is('input')){if($$.attr('src')){if($$.attr('src').match(/.*\.png([?].*)?$/i)){var source=(base&&$$.attr('src').search(/^(\/|http:)/i))?base+$$.attr('src'):$$.attr('src');$$.css({filter:hack.filter(source),width:$$.width(),height:$$.height()}).attr({src:$.ifixpng.getPixel()}).positionFix()}}}else{var image=$$.css('backgroundImage');if(image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)){image=RegExp.$1;image=(base&&image.substring(0,1)!='/')?base+image:image;$$.css({backgroundImage:'none',filter:hack.filter(image)}).children().children().positionFix()}}})}:function(){return this};$.fn.iunfixpng=hack.ltie7?function(){return this.each(function(){var $$=$(this);var src=$$.css('filter');if(src.match(/src=["']?(.*\.png([?].*)?)["']?/i)){src=RegExp.$1;if($$.is('img')||$$.is('input')){$$.attr({src:src}).css({filter:''})}else{$$.css({filter:'',background:'url('+src+')'})}}})}:function(){return this};$.fn.positionFix=function(){return this.each(function(){var $$=$(this);var position=$$.css('position');if(position!='absolute'&&position!='relative'){$$.css({position:'relative'})}})}})(jQuery);

/* copy to clipboard */
jQuery.copy=function(data){return jQuery.fn.copy.call({},data);};jQuery.fn.copy=function(delimiter){var me=this,flashcopier=(function(fid){return document.getElementById(fid)||(function(){var divnode=document.createElement('div');divnode.id=fid;document.body.appendChild(divnode);return divnode;})();})('_flash_copier'),data=jQuery.map(me,function(bit){return typeof bit==='object'? bit.value||bit.innerHTML.replace(/<.+>/g,''):'';}).join(delimiter||'').replace(/^\s+|\s+$/g,'')||delimiter,divinfo='<embed src="jquery.copy.swf"FlashVars="clipboard='+encodeURIComponent(data)+'"width="0"height="0"'+'type="application/x-shockwave-flash"></embed>';flashcopier.innerHTML=divinfo;return this;};

