/*
 *  Title: MAIN SCRIPT FOR CONTROLING THE COMMUNICATION FROM THE MAIN-UI PAGE TO THE BACKEND 
 *  Editors: Pramod, Hemant
 *  Description:
 *    
	- JS functions for sending parameters to the backend and receiving responses for purpose of:
		- showing tag-cloud,
		- enabling widgets content - Related-Content (tweets,news,Wikipedia), Entity-Relationship
 * 
 */

var EVENT_NAME_KEY = 'eventname';
var synchronizedGoogleNew = 0;

$(function() {
    
    initializeTabs();
    $('#eventChooser').selectmenu({
        change: function(e, obj) {
            if (obj.index === 0) return; // ignore selection of "Choose event..." option
            window.location.href = obj.value;
        }
    });
    $('#eventChooser').selectmenu('index', 0); // reset chooser to first option
    
    $('#selectDate img').hover(function(){
        $(this).css({'border-width': '3px', 'border-color': 'white', 'border-style':'solid'});
    },function(){
        $(this).css({'border-width': '0px', 'border-color': 'white', 'border-style':'solid'});
    });
    
    showEvent(Twitris.event, Twitris.eventDisplayName, Twitris.startDate, new Date(), 4, 10);
    
    $("#googlenews").show("slow");
    $("#eventDescription").show("slow");
    $("#dbpedia").show("slow");
    
    resetWidgets();
    
    // drawing of the flot graph must wait until the tab is shown because otherwise,
    // its width and height cannot be computed
    $('#tabs').bind('tabsshow', function(event, ui) {
        if(ui.index === 2){
            flotgraph(Twitris.event);
            $('#tabs').unbind('tabsshow', arguments.callee); // unbind this event listener after first fire
        }
    });
    
});

function resetWidgets(){
	$('#event_content').html("<p>Select a tag to see the relevant list of tweets</p>");
	$('#tweet_widget_head').html("<h4>Related Tweets</h4>");
	
	$('#googlenews_content').html("<p>Select a tag to see the related news items</p>");
	$('#news_widget_head').html("<h4>Reference Articles & News</h4>");	
	
	$('#db_content').html("<p>Select a tag to see the related Wikipedia entries</p>");
	$('#dbpedia_widget_head').html("<h4>Articles from Wikipedia</h4>");
}


function showEvent(eventID, eventDesc, minDate, maxDate, zoomLevel,tweetThreshold) {
//    $("#events_overlay").hide("slow");
//    $("#events").hide("slow");
    $("#curEvent").val(eventID);
    $('#date_event').val("event");
    $('#event_name').val(Twitris.event);
	
    fetchImages(eventID, eventDesc);
    fetchVideos(eventID, eventDesc);
    
}   


function displayMenu(){
    var left = ($(document).width() - $('#events').width()) / 2;

    $('#events_overlay').fadeIn();
    $('#events').css({"left" : left}).fadeIn();

    //clear displayed messages
    displayMessage("");
}

function hideMenu(){
showEvent('IndiaCorruption_s','India Anti-Corruption','2011/08/17',new Date(),4,10);
    $('#events_overlay').fadeOut();
    $('#events').fadeOut();	
    $('#startingBox').fadeOut();
}

function displayHowToBox(){
    $('#events_overlay').fadeIn();
    var left = ($(document).width() - $('#startingBox').width()) / 2;
    var top = ($(document).height() - $('#startingBox').height()) / 2 - 125;
    $('#startingBox').css({"left":left, "top": top});
//	$('#startingBox').show();
}

function showSpace(enablePoints) {

    if ( enablePoints === undefined ) {
        enablePoints = true;
    }


    $("#map_canvas").css( {
        'display' : 'block'
    });

}

// adds the closebutton to any div. when the button is clicked the parent is
// closed. The behavior on close is set as a data value to the parent and is
// eval-ed.
function addCloseButton(parent,overlay) {

    //log_console(parent.attr('id') + ' is the parent');
    var id = parent.attr('id') + "_close";
    //log_console(id);
    parent.append('<div id= "' + id + '" class="closeButton" style="width: 66px;"></div>');
    //log_console(parent.attr('id') + ' is the parent');
    var closeButtonElement = $('#' + id);
    var currentWidth = parseInt(closeButtonElement.css('width'));
    var padding = parseInt(parent.css("padding"));

    if (isNaN(padding)) {
        padding = 0;
    }

    closeButtonElement.css( {
        'left' : parseInt(parent.css("width")) - currentWidth + padding,
        'display' : 'block',
        'cursor' : 'pointer'

    });

    closeButtonElement.attr("title","Click here to close this dialog");

    closeButtonElement.click(function() {
        // remove the close button; is this better or just letting it stay and
        // not adding if one is present better?
        if (overlay != undefined) 	
            closeButtonAction($("#" + $(this).parent().get(0).id), overlay);
        else closeButtonAction($("#" + $(this).parent().get(0).id));
    //	$(this).remove();
    });
}

function closeButtonAction(parent,overlay) {
    parent.hide('slow');
    eval(parent.data('closeaction'));
}



/*
 * Fetch the news items
 * @param keywordText
 * @param date
 * @return
 */
function fetchTwitsixNews(keywordText, date) {
	
    // BECAUSE IT'S BEING CALLED IN frontend/twitrisMainPage/index.php and its using relative paths from there
    // var newsURL = "frontend/widgets/relatedTweetsArticles/newsArticles/get6news.php";
    var newsURL = "../widgets/relatedTweetsArticles/newsArticles/get6news.php";
	
    $.ajax( {
        url : newsURL,
        global : false,
        type : "GET",
        data : ({
            keyword : keywordText, //TODO pass the display name for this event ?
            date : date,
            event: Twitris.event
        }),
        dataType : "html", // return type is html
		
        beforeSend: function (xhr) {
            //update the header
            //	    	  displayHTMLMessage("<h3>Related news for " + keywordText + " [" + eventid  + "]</h3>" ,$('#news_widget_head'));
	    
            displayMessage("Loading related news items. Please Wait ..",$('#googlenews_content'));
        },

        success : function(data) {
            var contentDisplay = $('#googlenews_content');
                contentDisplay.html(data);
                contentDisplay.show("slow");
                contentDisplay.height('180px');
        },
	    
        error : function (XMLHttpRequest, textStatus, errorThrown) {
            displayMessage("Oops! There was an error in fetching the content!",$('#googlenews_content'));
        }

    });
}

/*
 * 
 * Fetch data for tweets & relevant external-articles widget
 * 
 */
function fetchTweetsArticleAnalysis(keywordText, date, widgetName, clusterLabel){
	
    // BECAUSE IT'S BEING CALLED IN frontend/twitrisMainPage/index.php and its using relative paths from there
    // var URL = "frontend/widgets/relatedTweetsArticles/tweets/getTweetForCloud.php";
    var URL = "../widgets/relatedTweetsArticles/tweets/getTweetForCloud.php";
    
    var data = {
        'term' : keywordText, 
        'date' : date,
        'event': Twitris.event,
        'widget': widgetName
    };
    
    if (clusterLabel) data.cluster_label = clusterLabel;
    
    $.ajax( {
        url : URL,
        global : false,
        type : "GET",
        data : data,
        dataType : "json", // return type is json
		
        beforeSend: function (xhr) {
            //update the header
            //  	  		 displayHTMLMessage("<h3></h3>" ,$('#tweet_widget_head'));
            displayMessage("Loading the relevant tweets ..",$('#event_content'));
        },

        success : function(data) {
            var contentDisplay = $('#event_content');
            contentDisplay.empty();

	 /*  JUST MAKING CASE BY CASE VIEW FOR TWEETS HEADER  , hemant  */
        //            var str = "<p class='title'>Distinct tweets for \"" + keywordText + "\" on "+date+" from "+clusterLabel+"</p>";
                var str = "<p class='title'>Tweets seen in the last 5 days for \"" + keywordText + "\""; 
                if(clusterLabel)
                        str = str + " from "+clusterLabel+"</p>";
          // -------------------------------------------------


            var tweet = data.tweet;
            if (tweet.length!=0){
                str += "<ul>";
                for(i=0;i<tweet.length;i++){
                    str += "<li>" + tweet[i]+"</li>";
                }
                str+="</ul>";
            }else{
                str += "There are no tweets to be shown!";
            }
	    	
	        
            //this is a json array
            contentDisplay.append(str);
            contentDisplay.show("slow");
            contentDisplay.height('180px');

            // Display external URL in google news widget
            return;
            contentDisplay = $('#googlenews_content');
	

		// JUST MAKING CASE BY CASE VIEW, hemant, nov. 20
           // var url_text = "<p class='title'>Reference articles for \"" + keywordText + "\" on "+date+" from "+clusterLabel+"</p>";
            	var url_text = "<p class='title'>Reference articles for \"" + keywordText + "\"" ;
		if(clusterLabel)	
			url_text = url_text + "	on "+date+" from "+clusterLabel;
		url_text = url_text +"</p>";

            var url = data.url;
            if (url.length!=0){
                url_text += "<ul>";
                for(i=0;i<url.length;i++){
			
		    if( url[i]=="null" )
			continue;
		if(url[i])
                    url_text += "<li>" + url[i]+"</li>";
                }
                url_text+="</ul>";
            } else {
                url_text = "";
            }
            if (synchronizedGoogleNew == 0){
                //alert('new');
                contentDisplay.html(url_text);
                synchronizedGoogleNew = 1;
                contentDisplay.show("slow");
                contentDisplay.height('180px');
            //alert('new');
            } else {
                //alert('append');
                contentDisplay.prepend(url_text);
                synchronizedGoogleNew = 0;
		    	
            }
	        
        //TODO update the div with the right heading ?
        },
        error : function (xhr, textStatus, errorThrown) {
            displayMessage("Oops! There was an error in fetching the content!",$('#event_content'));
        }
    });
}

/*
 * ***** Actually it's content was replaced into related-tweets function (see above function)
 *  because of showing analysis of external links, also in the news widget 
 */
function displayGoogleNews(data, contentDisplay){
}
/*
 * 
 * Fetch data from DBPedia-- for purpose of relatedTweetsArticles->Wikipedia widget
 * 
 */
function fetchDBPedia(keywordText){
	
    // BECAUSE IT'S BEING CALLED IN frontend/twitrisMainPage/index.php and its using relative paths from there
    // 	var dbpediaURL = "frontend/widgets/relatedTweetsArticles/wikipedia/getDBPediaInfo.php";
    var dbpediaURL = "../widgets/relatedTweetsArticles/wikipedia/getDBPediaInfo.php";
	
    $.ajax( {
        url : dbpediaURL,
        global : false,
        type : "GET",
        data : ({
            keyword : keywordText, 
            event : Twitris.event
        }),
        dataType : "html", // return type is html
		
        beforeSend: function (xhr) {
            //			  displayHTMLMessage("<h3>Articles about " + keywordText + " [" + eventName  + "]</h3>" ,$('#dbpedia_widget_head'));
            displayMessage("Loading relevant articles from Wikipedia ..",$('#db_content'));
        },

        success : function(data) {
            var contentDisplay = $('#db_content');
            contentDisplay.html(data);
            contentDisplay.show("slow");
            contentDisplay.height('180px');
		    
        //TODO update the div with the right heading ?
        },
	    
        error : function (XMLHttpRequest, textStatus, errorThrown) {
            displayMessage("Oops! There was an error in fetching the content!",$('#db_content'));
        }
    });
}

/**
 * Fetch images from flicker
 * 
 */

function fetchImages(eventID, eventDesc){
	
    // BECAUSE IT'S BEING CALLED IN frontend/twitrisMainPage/index.php and its using relative paths from there
    // var flickerURL = "fronted/widgets/multimedia/images/getFlickerImages.php";
    var flickerURL = "../widgets/multimedia/images/getFlickerImages.php";
    $.ajax( {
        url : flickerURL,
        global : false,
        type : "GET",
        data : ({
            keyword : eventDesc, 
            event : eventID
        }),
        dataType : "html", // return type is html
		
        beforeSend: function (xhr) {
            var contentDisplay = $('#tweetImage');
            //contentDisplay.hide();
            //			displayHTMLMessage("<h3>Articles about " + keywordText + " [" + eventName  + "]</h3>" ,$('#dbpedia_widget_head'));
            displayMessage("Loading related images..",$('#tweetImage'));
        },

        complete: function (xhr, textStatus) {
        //displayMessage("");
        },

        success : function(data) {
            var contentDisplay = $('#tweetImage');
            contentDisplay.html(data);
            var numberOfImages = ($("#tweetImage").width() - 35)/100 - 1; //3
            $(function() {
                $("#amazon_scroller3").amazon_scroller({
                    scroller_title_show: 'disable',
                    scroller_time_interval: '10000',
                    scroller_window_background_color: "none",
                    scroller_window_padding: '10',
                    scroller_border_size: '2', 
                    scroller_border_color: '#9C6',
                    scroller_images_width: '90',
                    scroller_images_height: '90',
                    scroller_title_size: '11',
                    scroller_title_color: 'black',
                    scroller_show_count: numberOfImages/*,
                    directory: 'images'*/
                });
            });
            
            $(".tooltip-target").ezpz_tooltip();
            //		    $.fn.ezpz_tooltip.positions.topLeft = function(contentInfo, mouseX, mouseY, offset, targetInfo) {
            ////		    	alert(mouseX + " " + mouseY);
            //		    	contentInfo['top'] = 0;
            //		    	contentInfo['left'] = 0;
            ////		    	alert(contentInfo);
            //		    	return contentInfo;
            //		    };
            //
            //		    $(".tooltip-target").ezpz_tooltip({
            //		    	contentPosition: 'rightFollow'
            //		    });
		    
            // turn these images into a lightbox gallery
            /*$('#amazon_scroller3 a').prettyPhoto({
		    	fixedNavigation: true
		    })*/
		    
		    
		    
		    
            contentDisplay.show("slow");
        //		    contentDisplay.height('180px');
		    
        //TODO update the div with the right heading ?
        },
	    
        error : function (XMLHttpRequest, textStatus, errorThrown) {
            displayMessage("Oops! There was an error in fetching the content!",$('#amazon_scroller3'));
        }
    });

}


/**
 * Fetch videos from YouTube
 * 
 */

function fetchVideos(eventID, eventDesc){
    // BECAUSE IT'S BEING CALLED IN frontend/twitrisMainPage/index.php and its using relative paths from there
    // var youTubeURL = "frontend/widgets/multimedia/video/fetchyoutubevideos.php";
    var youTubeURL = "../widgets/multimedia/videos/displayYoutubeVideos.php";
    $.ajax( {
        url : youTubeURL,
        global : false,
        type : "GET",
        data : ({
            keyword : eventDesc, 
            event : eventID
        }),
        dataType : "html", // return type is html
        beforeSend: function (xhr) {
            var contentDisplay = $('#tweetVideo');
            //contentDisplay.hide();
            displayMessage("Loading related videos..",$('#tweetVideo'));
        },
        success : function(data) {
            var contentDisplay = $('#tweetVideo');
            contentDisplay.html(data);
            var numberOfVideos = ($("#tweetVideo").width() - 35)/100 - 1;
            $("#amazon_scroller4").amazon_scroller({
                scroller_title_show: 'disable',
                scroller_time_interval: '10000',
                scroller_window_background_color: "none",
                scroller_window_padding: '10',
                scroller_border_size: '2', 
                scroller_border_color: '#9C6',
                scroller_images_width: '90',
                scroller_images_height: '90',
                scroller_title_size: '11',
                scroller_title_color: 'black',
                scroller_show_count: numberOfVideos
            });
		    
            contentDisplay.show("slow");
		    
            $('#amazon_scroller4 a').prettyPhoto();
        },
	    
        error : function (XMLHttpRequest, textStatus, errorThrown) {
            displayMessage("Oops! There was an error in fetching the content!",$('#tweetVideo'));
        }
    });

}


/**
 * Display messages
 * @return
 */
function displayMessage(message,messageDiv){
	
    if ( messageDiv === undefined ) {
        messageDiv = $('#loading_messages');
    }

    messageDiv.text(message);
}

/**
 * Display messages but with HTML
 * @return
 */
function displayHTMLMessage(message,messageDiv){
	
    if ( messageDiv === undefined ) {
        messageDiv = $('#loading_messages');
    }

    messageDiv.html(message);
}



function makeSearchAutocomplete() {
    
    $('#topic-search').autocomplete({
        source: function(request, response) {
            $.getJSON(
                '../searchInterface/searchQuerySuggestions.php', 
                {
                    event: encodeURIComponent(Twitris.event),
                    term: request.term
                },
                function(data) {
                    response(data);
                }
            );
        }
    });
    
    $('#topic-search-button').click(function() {
        var text = $('#topic-search').val();
        populateBottomWidgets(text, null, 'Search');
    });
    
}

function populateBottomWidgets(term, date, widgetName, cluster_label) {
    date = date || '';
    fetchTwitsixNews(term,
            date,
            $("#event_name").data(EVENT_NAME_KEY));
        // fetch dbpedia
        fetchDBPedia(term);
        // fetch relevant tweets & relevant external articles analysis
        fetchTweetsArticleAnalysis(term, date, widgetName, cluster_label);
        $("#tabs").tabs("select", 0);
        document.getElementById('tabs').scrollIntoView();
}


/**
 * Bind widget tab hide/show events to their respective hide/show methods in 
 * Twitris.widgets
 */
var initializeTabs = function() {
    var showWidgetByIndex = function(i) {
        // call .show() on newly selected widget, instantiating if necessary
        var name = Twitris.widgetMeta[i].name;
        var params = Twitris.widgetMeta[i].constructorParams;
        if (window[name]) {
            Twitris.widgets[name] = Twitris.widgets[name] || 
                (params ? new window[name](params) : new window[name]());
            if (typeof Twitris.widgets[name].show === 'function') Twitris.widgets[name].show();
        }
    };
    
    $('#top-tabs').data('selectedTab', 0);
    $('#top-tabs').tabs({
        show: function(event, ui) {
            // call .hide() on previously selected widget
            var hidingTabIndex = $(this).data('selectedTab'),
                hidingName = Twitris.widgetMeta[hidingTabIndex].name,
                hidingWidget = Twitris.widgets[hidingName];
            $(this).data('selectedTab', ui.index);
            if (hidingWidget && typeof hidingWidget.hide === 'function') hidingWidget.hide();
            showWidgetByIndex(ui.index);
        },
        create: function(event, ui) {
            $(this).tabs('select', 0);
            //showWidgetByIndex(ui.index);
        }
    });
    
    $("#tabs").tabs();
    $("#tabs").tabs("select",1);
    
};
