/**
 * Global Javascript functions for the WTT site
 */
jQuery.fn.fadeToggle = function(speed, easing, callback){
    this.animate({
        opacity: 'toggle'
    }, speed, easing, callback);
};

/**
 * Revert a trend back to a previous version number.
 * Only will work if the user has permissions to do so
 * @param {Object} trend_id
 * @param {Object} version_id
 */
function revertTrend(trend_id, version_id){

    jQuery.get("/api/v2/trend/revert?timestamp=" + new Date().getTime(), {
        "trend_id": trend_id,
        "blurb_id": version_id,
        "user_id": WhatTheTrend.user_id,
    }, function(data){
        if (data == false) {
            jQuery.prompt("Revert failed. You may be over your limit.");
        }
        else {
            jQuery("#blurbcontent").fadeOut();
            jQuery("#blurbcontent").queue(function(){
                jQuery(this).html(data);
                jQuery("#blurbta").val(data);
                jQuery(this).dequeue();
            });
            jQuery("#noblurb").hide();
            jQuery("#blurbcontent").fadeIn();
            if(WhatTheTrend) {
	            WhatTheTrend.blurbid = version_id;
				WhatTheTrend.enableVerifyButton(trend_id);
	        }
	        
            // replace blurb text on screen if it exists
            // setActiveVersion(version_id);
			// reloading this page until we get reverting right
			location.reload(true);
            
        }
    });
}

function setActiveVersion(version_id){
    var old_version = null;
    jQuery(".history_bullet > .revertButton").each(function(i){
        if (this.style.display == "none") {
            old_version = this;
        }
    });
    jQuery("#history_version_" + version_id + " > .revertButton").slideUp("fast");
    jQuery(old_version).slideDown("fast");
    jQuery(".history_bullet .edithistory").removeClass("current_text");
    jQuery("#history_version_" + version_id + " .edithistory").addClass("current_text");
}

/*
 * Global function for updating a trend asynchronously
 */
var WhatTheTrend = new function(){

    var id;
    var blurbid;
    var trendname;
    var trendnameencoded;
    var locked;
    var user_id = -1;
    var user_screen_name;
    
    //Public methods
    this.init = function(id, trend_name, trend_name_encoded, locked, search, user_id, user_screen_name, blurb_id){
        jQuery('.date').timeago();
        this.id = id;
        this.trendname = trend_name;
        this.trendnameencoded = trend_name_encoded;
        this.locked = locked;
        this.user_id = user_id;
        this.user_screen_name = user_screen_name;
        this.blurbid = blurb_id;
        
        enqueue(search + '&rpp=20&callback=WhatTheTrend.handleTwitter');
        //enqueue('http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=WhatTheTrend.handleFlickr&tags=' + WhatTheTrend.trendnameencoded);
        enqueue('http://ajax.googleapis.com/ajax/services/search/news?v=1.0&callback=WhatTheTrend.handleGoogle&rsz=large&q=' + WhatTheTrend.trendnameencoded);
    }
    this.handleTwitter = function(data){
        var parsed = eval(data);
        renderTwitter(parsed.results);
    }
    this.handleFlickr = function(data){
        var parsed = eval(data);
        renderFlickr(parsed.items);
    }
    this.handleGoogle = function(data){
        var parsed = eval(data);
        renderGoogle(parsed.responseData.results);
    }
    
    this.enableVerifyButton = function(trend_id, blurb_id) {
    	jQuery('#verify' + trend_id + "_" + blurb_id).css("opacity", "1");
        jQuery('#verify' + trend_id + "_" + blurb_id).attr("disabled");
    }

    this.disableVerifyButton = function(trend_id, blurb_id) {
    	jQuery('#verify' + trend_id + "_" + blurb_id).css("opacity", ".3");
        jQuery('#verify' + trend_id + "_" + blurb_id).removeAttr("disabled", "disabled");
    }

    this.enableVoteUpButton = function(trend_id, blurb_id) {
    	jQuery('#upbtn' + trend_id + "_" + blurb_id + ' img').attr("src", "/images/vote_up_active.png");
    	jQuery('#upbtn' + trend_id + "_" + blurb_id).css("opacity", "1");
    }

    this.disableVoteUpButton = function(trend_id, blurb_id) {
    	jQuery('#upbtn' + trend_id + "_" + blurb_id).css("opacity", ".3");
        jQuery('#upbtn' + trend_id + "_" + blurb_id).removeAttr("disabled", "disabled");
    }

    this.enableVoteDownButton = function(trend_id, blurb_id) {
    	jQuery('#downbtn' + trend_id + "_" + blurb_id + ' img').attr("src", "/images/vote_down_active.png");
    	jQuery('#downbtn' + trend_id + "_" + blurb_id).css("opacity", "1");
    }

    this.disableVoteDownButton = function(trend_id, blurb_id) {
    	jQuery('#downbtn' + trend_id + "_" + blurb_id).css("opacity", ".3");
        jQuery('#downbtn' + trend_id + "_" + blurb_id).removeAttr("disabled", "disabled");
    }
    
    this.editBlurb = function(){
    	
        if (this.user_id <= 0) {
            jQuery.prompt("You must be logged in to edit a definition. <a href='/login'>Log in now</a>.");
            return false;
        }
            	
        jQuery('#blurb').hide();
        jQuery('#related').hide();
        jQuery('#blurbform').show();
        jQuery('#edithints').show("slid");
        jQuery('#blurbta').height(jQuery('#blurb').height());
        this.autoresize(jQuery('#blurbta'));
    }
    this.saveBlurb = function(){
    
    	if(!jQuery("#blurbform").valid())
    	{
    		return;
    	}
    	
        var yourBlurb = jQuery('#blurbta').val();
        var user_screen_name_originator = jQuery('input[name=user_screen_name_originator]').val();
        var related_url = jQuery('input[name=related_url]').val();
        var categoryControl = jQuery("input[name=category]:checked");
        var recurring = jQuery("input[name=recurring]:checked").val();
        var yourCategory = -1;
        var your_user_screen_name = this.user_screen_name;
        if (categoryControl != null) {
            yourCategory = categoryControl.val();
        }
        //if(yourBlurb == null || yourBlurb == "")
        //{
        //	alert("You must add a definition");
        //	return;
        //}
        
        jQuery('#blurbta').attr("disabled", "disabled");
        jQuery('#okbtn').attr("disabled", "disabled");
        jQuery('#okbtn').text('Saving ...');
        jQuery('#cancelbtn').attr("disabled", "disabled");
        jQuery('.empty').removeClass('empty');
        var tweet = 'Q. Why is ' + this.trendname + ' trending? A. http://wttrend.com/' + this.id + ' ' + yourBlurb;
        jQuery('.rt a').attr('href', 'http://twitter.com/home?status=' + encodeURIComponent(tweet))
        jQuery.post('/api/v2/trend/update?trend_id=' + this.id, {
            blurb: yourBlurb,
            'trend_id': this.id,
            from: 'web',
            trend: this.trendname,
            'category_id': yourCategory,
            user_id: this.user_id,
            'user_screen_name': your_user_screen_name,
            'user_screen_name_originator': user_screen_name_originator,
            'related_url': related_url,
            'recurring': recurring            
        }, function(html){
            jQuery('#okbtn').text('OK');
            jQuery('#blurb').show();
            jQuery('#related').show();
            jQuery('#okbtn').removeAttr("disabled")
            jQuery('#cancelbtn').removeAttr("disabled")
            jQuery('#blurbta').removeAttr("disabled")
            jQuery('#blurbcontent').html(html);
            jQuery('#blurb_created').html("");
            if (yourCategory > 0) {
                cat_name = catIdToName(yourCategory);
                jQuery('#category_name').html(cat_name);
            }
            else {
                jQuery('#category_name').html('Unspecified');
            }
            
            if (user_screen_name_originator != '') {
                jQuery('#user_screen_name_originator').html("| Trend originated by <a href='http://twitter.com/" + user_screen_name_originator + "' target='_new'>@" + user_screen_name_originator + "</a>");
            }
            else {
                jQuery('#user_screen_name_originator').html('');
            }
            
            if (related_url != '') {
                jQuery('#related_url').html('<a href="' + related_url + '" target="_new" rel="nofollow">' + related_url + '</a>');
            }
            else {
                jQuery('#related_url').html('');
            }
            
            jQuery('#blurbform').hide();
            jQuery('#noblurb').hide();
            jQuery('#edithints').hide("slide");
            if (your_user_screen_name != undefined && your_user_screen_name != "") {
                jQuery("#editor_screen_name").html(" by <a href='/users/" + user_id + " target='_new'>@" + your_user_screen_name + "</a>")
            }
            if (typeof(TrendHistory) != 'undefined') {
                TrendHistory.loadHistory(WhatTheTrend.trendnameencoded);
            }
        }, 'html');
    }

    this.verifyBlurb = function(trend_id, user_id, blurb_id){
        if (user_id <= 0) {
            jQuery.prompt("You must be logged in to verify a definition. <a href='/login'>Log in now</a>.");
            return false;
        }
        
        if ( blurb_id === undefined ) {
      		blurb_id = this.blurbid;
   		}

        this.disableVerifyButton(trend_id, blurb_id);
        jQuery.post('/trend/' + trend_id + '/verify?blurb_id=' + this.blurbid + '&timestamp=' + new Date().getTime(), {
            'trend_id': trend_id,
            'user_id': user_id
        }, function(html){
        	if(html == "false")
        	{
        		jQuery.prompt("Unable to verify definition.");
	            this.enableVerifyButton(trend_id, blurb_id);
        	}
        	else
        	{
				jQuery('#verify' + trend_id + "_" + blurb_id).html("Verified");
        	}
            if (typeof(TrendHistory) != 'undefined') {
                TrendHistory.loadHistory(WhatTheTrend.trendnameencoded);
            }	        
        }, 'html');
    }

    this.voteUpBlurb = function(trend_id, user_id, blurb_id){
        if (user_id <= 0) {
            jQuery.prompt("You must be logged in to vote. <a href='/login'>Log in now</a>.");
            return false;
        }

        if ( blurb_id === undefined ) {
      		blurb_id = this.blurbid;
   		}

        WhatTheTrend.disableVoteUpButton(trend_id, blurb_id);
        WhatTheTrend.disableVoteDownButton(trend_id, blurb_id);
        
        jQuery.post('/api/v2/blurb/' + blurb_id + '/voteUp?timestamp=' + new Date().getTime(), {
            'trend_id': trend_id,
            'user_id': user_id
        }, function(html){
        	if(html == "false")
        	{
        		jQuery.prompt("Unable to vote. You can only vote once, and you may not vote on your own definition.");
	            jQuery('#upbtn' + trend_id + "_" + blurb_id).css("opacity", "1");
	            jQuery('#downbtn' + trend_id + "_" + blurb_id).css("opacity", "1");
        	}
        	else
        	{
        		WhatTheTrend.enableVoteUpButton(trend_id, blurb_id);
	            if (html != '') {
	                jQuery('#score' + trend_id).html(html);
	                jQuery('#score' + trend_id + "_" + blurb_id).html(html);
	            }
	        }
        }, 'html');
    }
    this.voteDownBlurb = function(trend_id, user_id, blurb_id){
        if (user_id <= 0) {
            jQuery.prompt("You must be logged in to vote. <a href='/login'>Log in now</a>.");
            return false;
        }
        
        if ( blurb_id === undefined ) {
      		blurb_id = this.blurbid;
   		}

        WhatTheTrend.disableVoteUpButton(trend_id, blurb_id);
        WhatTheTrend.disableVoteDownButton(trend_id, blurb_id);

        jQuery.post('/api/v2/blurb/' + blurb_id + '/voteDown?timestamp=' + new Date().getTime(), {
            'trend_id': trend_id,
            'user_id': user_id
        }, function(html){
        	if(html == "false")
        	{
        		jQuery.prompt("Unable to vote. You can only vote once, and you may not vote on your own definition.");
	            jQuery('#upbtn' + trend_id + "_" + blurb_id).css("opacity", "1");
	            jQuery('#downbtn' + trend_id + "_" + blurb_id).css("opacity", "1");
        	}
        	else
        	{
        		WhatTheTrend.enableVoteDownButton(trend_id, blurb_id);
	            if (html != '') {
	                jQuery('#score' + trend_id).html(html);
	                jQuery('#score' + trend_id + "_" + blurb_id).html(html);
	            }
	        }
        }, 'html');
    }
    this.flagBlurb = function(trend_id, user_id, blurb_id) {
        if (user_id <= 0) {
            jQuery.prompt("You must be logged in to flag items. <a href='/login'>Log in now</a>.");
            return false;
        }
        
        if ( blurb_id === undefined ) {
      		blurb_id = this.blurbid;
   		}

    	var button_key = '#flagbtn' + trend_id + "_" + blurb_id;

        jQuery(button_key).attr("disabled", "disabled");
        jQuery(button_key).text('Saving ...');
        jQuery.post('/api/v2/blurb/' + blurb_id + '/flag?timestamp=' + new Date().getTime(), {
            'trend_id': trend_id,
            'user_id': user_id
        }, function(html){
        	if(html == "false")
        	{
        		jQuery.prompt("Unable to flag item. You can only flag an item once, and you may not flag your own definition.");
	            jQuery(button_key).text('Flag as Inappropriate');
	            jQuery(button_key).css("opacity", "1");
        	}
        	else
        	{
	            jQuery(button_key).text('Flagged');
	            jQuery(button_key).css("opacity", "1");
	            jQuery(button_key).css("background-color", "maroon");
	            jQuery(button_key).css("color", "white");
	        }        
        }, 'html');
    }
    this.cancelBlurb = function(){
        jQuery('#blurb').show();
        jQuery('#related').show();
        jQuery('#blurbform').hide();
        jQuery('#edithints').hide("slide");
    }
    
    this.autoresize = function(text, maxHeight){
        var adjustedHeight = text.clientHeight;
        if (!maxHeight || maxHeight > adjustedHeight) {
            adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
            if (maxHeight) 
                adjustedHeight = Math.min(maxHeight, adjustedHeight);
            if (adjustedHeight > text.clientHeight) 
                text.style.height = adjustedHeight + "px";
        }
    }
    //Private methods
    function enqueue(url){
        var script = document.createElement('script');
        script.type = "text/javascript";
        script.src = url;
        document.getElementsByTagName('head')[0].appendChild(script);
    }
    function renderTwitter(results){
        jQuery('#tweets').empty();
        for (var i = 0; i < Math.min(results.length, 15); i++) {
            var div = document.createElement('div');
            div.className = 'tweet';
            var tweet = results[i]
            div.innerHTML = ('<a href="http://twitter.com/' + tweet.from_user + '"><img src="' + tweet.profile_image_url + '" alt="" width="48" height="48" /></a><a href="http://twitter.com/' + tweet.from_user + '">' + tweet.from_user + "</a> " + autolink(tweet.text));
            jQuery('#tweets').append(div);
        }
    }
    function renderFlickr(results){
        jQuery('#fphotos').empty();
        for (var i = 0; i < Math.min(results.length, 2); i++) {
            var div = document.createElement('div');
            div.className = 'fphoto';
            var fphoto = results[i];
            div.innerHTML = '<p class="im"><a href="' + fphoto.link + '"><img src="' + fphoto.media.m + '" alt="' + fphoto.title + '"  /></a></p><p class="caption">' + fphoto.title + '</p>';
            jQuery('#fphotos').append(div);
        }
        
    }
    function renderGoogle(results){
        jQuery('#garticles').empty();
        for (var i = 0; i < Math.min(results.length, 10); i++) {
            var div = document.createElement('div');
            div.className = 'garticle';
            var garticle = results[i];
            div.innerHTML = '<p><a href="' + garticle.unescapedUrl + '">' + garticle.titleNoFormatting + '</a> (' + garticle.publisher + ')<br>' + garticle.content + '</p>';
            jQuery('#garticles').append(div);
        }
        
    }
    function autolink(input){
        return input.replace(/(ftp|http|https|file):\/\/[\S]+(\b|$)/gim, '<a href="$&">$&</a>').replace(/([^\/])(www[\S]+(\b|$))/gim, '$1<a href="http://$2">$2</a>');
    }
    
    this.attachLoginBoxes = function(){
		
        jQuery('.require_login').each(function(){
            // options
            var distance = 20;
            var time = 250;
            var hideDelay = 500;
            
            var hideDelayTimer = null;
            
            // tracker
            var beingShown = false;
            var shown = false;
            
            var trigger = jQuery(this);
            var popup = jQuery('.login_popup').css('opacity', 0);
            
            // set the mouseover and mouseout on both element
            jQuery(this).mouseover(function(){
                
                var top_pos = trigger.position().top + 30;
                var left_pos = trigger.position().left;

                // reset position of popup box
                popup.css({
                	left: left_pos,
                	top: top_pos,
                    opacity: 1,
                    display: 'block' // brings the popup back in to view
                });
            })
        });
    }
	
	this.hideLoginBox = function(box) {
		jQuery(box).css({
			opacity: 0,
			display: 'none'
		});
	}

}

function catIdToName(catid){
    var catName = '';
    switch (catid) {
        case ("1"):
            catName = "Entertainment";
            break;
        case ("2"):
            catName = "Gaming";
            break;
        case ("3"):
            catName = "Lifestyle";
            break;
        case ("4"):
            catName = "Science";
            break;
        case ("5"):
            catName = "Sports";
            break;
        case ("6"):
            catName = "Technology";
            break;
        case ("7"):
            catName = "Business";
            break;
        case ("8"):
            catName = "SPAM";
            break;
        case ("9"):
            catName = "Meme";
            break;
        case ("10"):
            catName = "Conference/Event";
            break;
        case ("11"):
            catName = "News";
            break;
        case ("12"):
            catName = "Place/Location";
            break;
        case ("13"):
            catName = "Holiday/Calendar";
            break;
        case ("14"):
            catName = "Other";
            break;
        default:
            catName = "Unspecified";
            break;
    }
    
    return catName;
}

function countryToFlag(country){
    var country_image = '';
    switch (country) {
        case ("United States"):
            country_image = "us.png";
            break;
        case ("Canada"):
            country_image = "ca.png";
            break;
        case ("United Kingdom"):
            country_image = "gb.png";
            break;
        case ("Philippines"):
            country_image = "ph.png";
            break;
        case ("Brazil"):
            country_image = "br.png";
            break;
        case ("Australia"):
            country_image = "au.png";
            break;
        case ("Germany"):
            country_image = "de.png";
            break;
        case ("India"):
            country_image = "in.png";
            break;
        case ("China"):
            country_image = "cn.png";
            break;
        case ("Norway"):
            country_image = "no.png";
            break;
        case ("Ireland"):
            country_image = "ie.png";
            break;
        case ("Puerto Rico"):
            country_image = "pr.png";
            break;
        case ("Netherlands"):
            country_image = "nl.png";
            break;
        case ("Switzerland"):
            country_image = "ch.png";
            break;
        case ("Singapore"):
            country_image = "sg.png";
            break;
        case ("Denmark"):
            country_image = "dk.png";
            break;
        case ("France"):
            country_image = "fr.png";
            break;
        case ("Mexico"):
            country_image = "mx.png";
            break;
        case ("Indonesia"):
            country_image = "id.png";
            break;
        case ("Dominican Republic"):
            country_image = "do.png";
            break;
        case ("Poland"):
            country_image = "pl.png";
            break;
        case ("Hong Kong"):
            country_image = "hk.png";
            break;
        case ("Japan"):
            country_image = "jp.png";
            break;
        case ("New Zealand"):
            country_image = "nz.png";
            break;
        case ("Spain"):
            country_image = "es.png";
            break;
        case ("Venezuela"):
            country_image = "ve.png";
            break;
        case ("Italy"):
            country_image = "it.png";
            break;
        case ("Chile"):
            country_image = "cl.png";
            break;
        case ("Argentina"):
            country_image = "ar.png";
            break;
        case ("Turkey"):
            country_image = "tr.png";
            break;
        case ("Colombia"):
            country_image = "co.png";
            break;
        case ("United Arab Emirates"):
            country_image = "ae.png";
            break;
        case ("Ecuador"):
            country_image = "ec.png";
            break;
        case ("Malaysia"):
            country_image = "my.png";
            break;
        case ("South Africa"):
            country_image = "za.png";
            break;
        case ("Peru"):
            country_image = "pe.png";
            break;
        case ("Nigeria"):
            country_image = "ng.png";
            break;
        case ("Sweden"):
            country_image = "se.png";
            break;
        default:
            country_image = "default.png";
            break;
    }
    
    if (country_image != "") {
        country_image = "http://www.whatthetrend.com/images/flags/" + country_image;
    }
    
    return country_image;
}

