var _mouseX = 0;
var _mouseY = 0;
var _animationInProgress = false;

//on page load call util functions
$(document).ready(function(){   
	showThumbPreview ();	
	slideGallery();
	
	
	$().mousemove( function(e) {
	  _mouseX = e.pageX;
	  _mouseY = e.pageY;
    });
});


/* Shows thumbpreview on resource browser */

function showThumbPreview () {
	var elem = $('#resourceBrowser .storyBox');
	$(elem).hover( 
		function(){
			$(this).css("zIndex", "10");
			$(this).addClass("storyBoxHover");
		},
		function(){
			$(".storyBox").css("zIndex", "2");
			$(this).removeClass("storyBoxHover");
		}
	);
}


function onTagClick(strTagID, blnIsSeeAllStories)
{
    var strTagStoryIDs = "";
    if(blnIsSeeAllStories == 0)
    {
        var a = document.getElementById("usrSOSClouds_" + strTagID);
        strTagStoryIDs = a.getAttribute('storyids');
    }
    else
    {
        strTagStoryIDs = "";
    }      
    markInActive(strTagStoryIDs, blnIsSeeAllStories);
}

function markInActive(strTagStoryIDs, blnIsSeeAllStories)
{
    var pageContentDiv = document.getElementById("SOSContentDiv");
    pageContentDiv.style.display = "none";
    var listingDiv = document.getElementById("SOSListingDiv");    
    listingDiv.style.display = "block";
    
    var listingContentDiv = document.getElementById("SOSListingContentDiv");
    var strlistingDiv = "";
    strlistingDiv = strlistingDiv + "<div>";
    strlistingDiv = strlistingDiv + "<table cellspacing='0' border='0' id='gvStoryResults' >";
    
    var i = 0, n = 0;
    var elementImageCloud;    
    elementImageCloud = document.getElementById("ImageCloudSliderDiv");
    var aTags = elementImageCloud.getElementsByTagName('a');
    var aTotal = aTags.length;
    var blnIsTagStory = 0;
    
    strArrStoryIDs = strTagStoryIDs.split(',');
    
    var arrStoriesListingID = new Array();
    var arrStoriesListingHref = new Array();
    var arrStoriesListingHeadline = new Array();
    var arrStoriesListingCreationDate = new Array();
    
    var iTagStoryCount = 0;
    
	for(i = 0; i < aTotal; i++ )
	{
	    if(blnIsSeeAllStories == 0)
        {
            // a Tag is clicked
	        intStoryID = aTags[i].getAttribute('storyid');
	        blnIsTagStory = 0;
            for(n = 0; n < strArrStoryIDs.length; n++)
            {
                intTagStoryID = strArrStoryIDs[n];
                if (intStoryID == intTagStoryID)
                {
                    blnIsTagStory = 1;
                                        
                    arrStoriesListingID[iTagStoryCount] = "listing_" + aTags[i].id;
                    arrStoriesListingHref[iTagStoryCount] = aTags[i].getAttribute('href');
                    arrStoriesListingHeadline[iTagStoryCount] = aTags[i].getAttribute('headlinetext');
                    arrStoriesListingCreationDate[iTagStoryCount] = aTags[i].getAttribute('creationdate');
                                        
                    iTagStoryCount++;
                    break;
                }
            }
            
            var elementST = aTags[i];
            var parentStoryBoxDiv = elementST.parentNode;
            var divExtra = parentStoryBoxDiv.getElementsByTagName('div');
            var divExtraArrLength = divExtra.length;

            var blnIsDim = 0;
            
            if(divExtraArrLength != 0)
            {
                strTest = divExtra[0].id.toLowerCase();
                if(strTest.indexOf("extra_") == -1)
                {
                    blnIsDim = 0;
                }
                else
                {
                    blnIsDim = 1;
                }
            }
            else
            {
                blnIsDim = 0;
            }
            
	        if( ((blnIsTagStory == 1) && (blnIsDim == 0)) ||  ((blnIsTagStory == 0) && (blnIsDim == 1)) )
	        {
    	        
	        }   
	        else
	        {
	            if( (blnIsTagStory == 0) && (blnIsDim == 0) )
	            {
	                //make dim
                    var elementSTSpan = elementST.getElementsByTagName('span');
                    var elementSpanImage = elementSTSpan[0].getElementsByTagName('img');
                    var elementSpanFiltered = "<span id='" + elementSTSpan[0].id + "' class='filtered' >";
                    
                    elementSpanFiltered = elementSpanFiltered + "<img id='" + elementSpanImage[0].id + "' src='" + elementSpanImage[0].getAttribute('src') + "' />";
                    elementSpanFiltered = elementSpanFiltered +  "</span>";
                    
                    elementST.style.display = "none";
                    elementST.style.visibility="hidden";
                    
                    parentStoryBoxDiv.innerHTML = parentStoryBoxDiv.innerHTML + elementSpanFiltered;
                    parentStoryBoxDiv.innerHTML = parentStoryBoxDiv.innerHTML + "<div id='Extra_" + elementST.id + "' ></div>";              
	            }
        	    
	            if( (blnIsTagStory == 1) && (blnIsDim == 1) )
	            {
	                //make active
                    var strActive = "<a id='" + elementST.id + "' href='" + elementST.getAttribute('href') + "' headlinetext='" + elementST.getAttribute('headlinetext') + "' creationdate='" + elementST.getAttribute('creationdate') + "' storyid='" + elementST.getAttribute('storyid') + "' >";
                    strActive = strActive + elementST.innerHTML + "</a>";
                    
                    parentStoryBoxDiv.innerHTML = strActive;
                    $("#storyBrowserContainer .storyBox a").bind("mouseover", function() {showThumbsPreview($(this));});                
	            }
            }
        }
        else
        {
            // See All Stories is clicked
            var elementStoryAnchors = aTags[i];            
            
            arrStoriesListingID[i] = "listing_" + elementStoryAnchors.id;
            arrStoriesListingHref[i] = elementStoryAnchors.getAttribute('href');
            arrStoriesListingHeadline[i] = elementStoryAnchors.getAttribute('headlinetext');
            arrStoriesListingCreationDate[i] = elementStoryAnchors.getAttribute('creationdate');
                    
            // rebuild all the images in image cloud as active
            var strActive = "<a id='" + elementStoryAnchors.id + "' href='" + elementStoryAnchors.getAttribute('href') + "' headlinetext='" + elementStoryAnchors.getAttribute('headlinetext') + "' creationdate='" + elementStoryAnchors.getAttribute('creationdate') + "' storyid='" + elementStoryAnchors.getAttribute('storyid') + "' >";
            strActive = strActive + elementStoryAnchors.innerHTML + "</a>";
            
            var parentStoryBoxDiv = elementStoryAnchors.parentNode;            
            parentStoryBoxDiv.innerHTML = strActive;
            $("#storyBrowserContainer .storyBox a").bind("mouseover", function() {showThumbsPreview($(this));});
        }
	}

    function story(StoryID, StoryHref, StoryHeadline, StoryCreationDate) 
    {
        this.SId = StoryID;
        this.SHref = StoryHref;
        this.SHeadline = StoryHeadline;
        this.SCreationDate = StoryCreationDate;
    }
    
    function sortByHeadline(a, b)
    {
        var x = a.SHeadline.toLowerCase();
        var y = b.SHeadline.toLowerCase();
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    }
    
    var totalHeadlines;
        	
    if(blnIsSeeAllStories == 0)
    {
        totalHeadlines = iTagStoryCount;
	}
	else
	{
        totalHeadlines = aTotal;
    }     
    
    var arrStories = new Array();
    for(i = 0; i < totalHeadlines; i++ )
    {
        arrStories[i] = new story(arrStoriesListingID[i], arrStoriesListingHref[i], arrStoriesListingHeadline[i], arrStoriesListingCreationDate[i]);
    }
    
    arrStories.sort(sortByHeadline);
    
    for(i = 0; i < totalHeadlines; i++ )
    {	        
        // build the Story Listing Div tag
        strlistingDiv = strlistingDiv + "<tr>";

        strlistingDiv = strlistingDiv + "<td>";    
        strlistingDiv = strlistingDiv + "<a id='listing_" + arrStories[i].SId + "' href='" + arrStories[i].SHref + "' class='internalLink' >" + arrStories[i].SHeadline + "</a>";
        strlistingDiv = strlistingDiv + "</td>";
        
        strlistingDiv = strlistingDiv + "</tr>";	        
    }
	
	strlistingDiv = strlistingDiv + "</table>";
    strlistingDiv = strlistingDiv + "</div>";
    
    listingContentDiv.innerHTML = strlistingDiv;
}

/* Calculate the width of the SlideContent to have all storyboxes in three rows */
function slideGallery() {
	var element = $("#sliderContainer #sliderContent .sliderDiv div.storyBox");
	var elementCount = element.length;
	var elementWidth = element.outerWidth();
	var elementHeight = element.outerHeight();
	
	// calcualte maxwidth to get all images into three rows
	var containerWidth = (elementCount / 3) * elementWidth;
	// set width to slider container
	var sliderContainer = $("#sliderContainer #sliderContent .sliderDiv");
	sliderContainer.css("width", containerWidth);
	
	if (parseInt(sliderContainer.css("left")) <= 80 ){
//		$("#storyBrowserContainer #lnkSlideLeft").css("display","none");
		$("#storyBrowserContainer #divSlideLeft").css("background-position","-170px 5px");
		$("#storyBrowserContainer #lnkSlideLeft").hide();
	}
	
	//width corresponding to 30 images
	if (containerWidth <= 650 ){
//		$("#storyBrowserContainer #lnkSlideLeft").css("display","none");
		$("#storyBrowserContainer #divSlideRight").css("background-position","-170px 5px");
	    $("#storyBrowserContainer #lnkSlideRight").hide();
	}
	
	// hover event - change background position
	$("#lnkSlideLeft,#lnkSlideRight").hover(
		function () {
			var div = $(this).parent();
			var bgPos = parseInt(div.css("background-position"));
			if(jQuery.browser.msie && jQuery.browser.version <= 7){
				bgPos = parseInt(div.css("background-position-x"));
			}
			if (bgPos != -170){
				div.css("background-position","-85px 5px");
			}
		}, 
		function () {
			var div = $(this).parent();
			var bgPos = parseInt(div.css("background-position"));
			if(jQuery.browser.msie && jQuery.browser.version <= 7){
				bgPos = parseInt(div.css("background-position-x"));
			}
			if (bgPos != -170){
				div.css("background-position","0px 5px");
			}
		}
	);
	
	$("#storyBrowserContainer #lnkSlideLeft").bind("click", function() {
//			$("#storyBrowserContainer #lnkSlideRight").css("display","block");
			$("#storyBrowserContainer #divSlideRight").css("background-position","0px 5px");
			slideLeft(sliderContainer, elementWidth);
		});
	$("#storyBrowserContainer #lnkSlideRight").bind("click", function() {
//			$("#storyBrowserContainer #lnkSlideLeft").css("display","block");
			$("#storyBrowserContainer #divSlideLeft").css("background-position","0px 5px");
			slideRight(sliderContainer, elementWidth);
	});


	
	
	$("#storyBrowserContainer .storyBox a").bind("mouseover", function() {
		showThumbsPreview($(this));
	});
	
	$("#storyBrowserContainer #divSlideLeft,#storyBrowserContainer #divSlideRight").bind("mouseover", function() {
		hideThumbsPreview();
	});
	
	$("#storyBrowserFooter").bind("mouseleave", function() {
		hideThumbsPreview();
	});
	
	// timer to avoid dirty remaining popups 
//	$(document).everyTime(1000, function(i) {
//	  // check if popup is rendered
//	  if($("#thumbspreview").length > 0) {
//		 // hideThumbsPreview();
//		 var left = $("#sliderContainer").offset().left;
//		 var top = $("#sliderContainer").offset().top;
//		 var right = $("#sliderContainer").offset().left + $("#sliderContainer").width();
//		 var bottom = $("#sliderContainer").offset().top + $("#sliderContainer").height();
//		 
//		 // check if mouse pinter is in the gallery
//		 if(! ((_mouseX >= left && _mouseX <= right) && (_mouseY >= top && _mouseY <= bottom))) {
//			 hideThumbsPreview();
//		 }
//	  }
//	}, 0);
	
}

// Move/Slide box to the right, distance equals the width of one element/picture
function slideRight(container, distance) {
	if(!_animationInProgress) 
	{
		_animationInProgress = true;

	    //to which point has the box to be moved (position: left)
	    var newDistance = parseInt(container.css("left"))-distance;
	    //width of the slide container including the initial left distance
	    var containerWidth = container.outerWidth()+parseInt(container.parent().parent().css("padding-left"));
	    //width of the viewport
	    var viewPort = container.parent().parent().outerWidth();
	    //how much is left which can be moved
	    var leftSpace = containerWidth+newDistance-viewPort;
    		
	    if (leftSpace >= 0) 
	    {
		    container.animate({
			    left: newDistance			  
		    }, 1500, 'linear', function(){ _animationInProgress = false; } );
		    if (leftSpace == 5 )
		    {
    //			$("#storyBrowserContainer #lnkSlideRight").css("display","none");
			    $("#storyBrowserContainer #divSlideRight").css("background-position","-170px 5px");
			    $("#storyBrowserContainer #lnkSlideRight").hide();
		    }
		    $("#storyBrowserContainer #lnkSlideLeft").show();
		}
	}
}

// Move/Slide box to the left, distance equals the width of one element/picture
function slideLeft(container, distance) {
	if(!_animationInProgress) {
		_animationInProgress = true;
		
		//to which point has the box to be moved (position: left)
		var newDistance = parseInt(container.css("left"))+distance;
		// only animate if left position is less than initial position
		if (newDistance-parseInt(container.parent().parent().css("padding-left")) <= 0) {
			container.animate({
				left: newDistance			  
			}, 1500, 'linear', function(){ _animationInProgress = false; } );
			
			if (newDistance-parseInt(container.parent().parent().css("padding-left")) == -5 ){
	//			$("#storyBrowserContainer #lnkSlideLeft").css("display","none");
				$("#storyBrowserContainer #divSlideLeft").css("background-position","-170px 5px");
				$("#storyBrowserContainer #lnkSlideLeft").hide();
			}
			$("#storyBrowserContainer #lnkSlideRight").show();
		}
	}
}

// Show preview box and position it
function showThumbsPreview(element) {
    //debugger;
	if ($("#thumbspreview").length == 0) {
		$(document.body).append("<div id=\"thumbspreview\"></div>");
	}
	$("#thumbspreview").html(element.parent().clone(true).html());
	
	var thumb = $("#thumbspreview a span");
	thumb.parent().addClass("current");
	thumb.css("top", parseInt(element.offset().top)+parseInt(thumb.css("top")));
	thumb.css("left", parseInt(element.offset().left)+parseInt(thumb.css("left")));	
	
	highlightLinkOnThumbPreview(thumb);
	
	$("#thumbspreview").bind("mouseleave", function() {
		hideThumbsPreview();
	});
}

function hideThumbsPreview() {	
	$("#resourceBrowser").find(".active").removeClass("active");
	$("#thumbspreview").find("em").unbind();
	$("#thumbspreview").empty();
	$("#thumbspreview").unbind();
	$("#thumbspreview").remove();
}


/* Highlight title text on hover in thumbpreview */
/* addClass and removeClass does not work in IE */
function highlightLinkOnThumbPreview (thumb) {
	thumb.find("em").bind (
			"mouseenter", function() {
				//$(this).addClass("active");
				$(this).css("color","#f49500");
			}
	);
	
	thumb.find("em").bind (
			"mouseleave", function() {
				//$(this).removeClass("active");
				$(this).css("color","#ffffff");
			}
	);	
}
