preload();


var hooks = {
	'_hooks': {},
	
	'hookTo': function(hookName, func) {
		_hookList = (typeof(this._hooks[hookName]) == 'object') ? this._hooks[hookName] : this._hooks[hookName] = new Array();
		_hookList[_hookList.length] = func;
	},
	
	'trigger': function(hookName, param) {
		j$.each( this._hooks[hookName], function(i, func) { func(param) } );
	},

	'debug': function() {
		console.dir(this._hooks);
	}

};

var horizon = {
	initShare : false,
	openMode : 'page',
	uri : gup2('uri'),
	configid: getCustomerId(), 
	fb_connect : '<a href="#" class="fb_button" id="fbConnect">Connect</a><p><b></b>See what your friends are interested in</p>',	
	catArr : null,
	oldBrowser : false,
	path : "/Services/FrontService/",
	sessionId : generateGuid(),
	widgets: j$('div.headupwidget')
}

/* DEPLOYMENT FOR PRODUCTION */
var settings = {
	RealTimeHandler: 'http://XXX_ENTRYURL_XXX/Services/RealTime/RealTime.ashx',
	RealTimeHandler: 'http://localhost/Services/RealTime/RealTime.ashx', // RemoveThisLocalhostLineOnDeploy
	facebookApiKey: '8a457346a7e5c5e57806ea0f6665e7c3',
	facebookApiKey: '5ab946f0b858ec1e2d2f002c5944037a', // RemoveThisLocalhostLineOnDeploy
	xd_reciverPath: '/Services/FrontService/Auth/FacebookConnect/xd_receiver.htm'
};

function preload() {
    // Allow only these customer id's
    /*
    var allowedFlag = false, allowedLength = _headup.allowedConfigs.length;
    while( allowedLength-- ){
    if( this.customer.toLowerCase() == _headup.allowedConfigs[allowedLength] ){
    allowedFlag = true;
    break;
    }
    }
    if( !allowedFlag && typeof hc_allow == 'undefined' )
    return false;
    */
	
	
    //if (this.preloaded)
      //  return;

	  
	  
//    this.old$ = typeof $ != 'undefined' ? $ : "";

//    this.jquery_hack = false; // if true, means useing hjquery because there is another jquery already on the page (older version), and we don't want to mess with that
//    this.preloaded = true;
//    // get jQuery version and parse it to a number 1.4.2 -> 142
//    var jQVersion = typeof jQuery == 'undefined' ? 0 : Number(jQuery().jquery.replace(/\./g, ''));
//    // check if the jQuery on the page version is what Headup needs, is less, than load hJquery (play nice with onpage script)
//    var jqueryUrl_local = this.cdnHost + 'hjquery-1.4.2.min.js?v1';
//    var jqueryUrl = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';

//    if (!jQVersion)
//        this.loadScript(jqueryUrl, function () { _headup.onJQueryReady() });
//    else if (jQVersion < 130) {
//        _headup.jquery_hack = true;
//        this.loadScript(jqueryUrl_local, function () {
			if(typeof j$ == "undefined")
			{
				j$ = hjquery.noConflict();
				if (this.old$)
					$ = this.old$;

				j$.ajaxSetup({ cache: true });
			}
            //var jqueryUi_Url = _headup.cdnHost + 'jquery-ui-1.7.1.custom.min.js';
        
        //});
//    }
//    else
//        this.onJQueryReady();
}

j$.fn.center = function(){
	this.css("margin-top", -this.outerHeight() / 2 + "px");
	this.css("margin-left", -this.outerWidth() / 2 + "px");
	return this;
}

function gup2() {
	var uri = window.location.href;
	//try long url
	var index = uri.indexOf('dbpediaSubject');
	if (index != -1) {
		//try long url
		var start = uri.indexOf('dbpediaSubject') + 'dbpediaSubject'.length;
		if (start == -1)
			return null;
		var end = uri.indexOf('/', start + 1);
		return uri.substring(start + 1, end);
	} else if ($_foundCanon = j$('link[rel="canonical"]').attr("href")) {
		return $_foundCanon.split("/").pop();
	} else if (uri.indexOf("uri=") != -1) {
		uri = uri.substring(uri.indexOf("uri=") + 4);
		if (uri.match(/#[0-9]+$/)) {
			uri = uri.substring(0, uri.lastIndexOf("#"));
		}
		return uri.split("&").shift();
	} else
		return uri.split("/").pop();
}

function getCustomerId(){
	var meta = j$("meta[name='customerid']");
	if(meta)
		return meta.attr('content');
	
	return 'unknown';
}

function getReferrer(){
	try{
		if (!document.referrer) {
			return null;
		}
		else {
			return escape(document.referrer);
		}
	}
	catch (err){
        ShowLog('getReferrer', err);
		return null;
    }
}

cookies = {
	create : function(name,value,days) {
		var expires;
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			expires = "; expires="+date.toGMTString();
		}
		else
			expires = "";
		document.cookie = name+"="+ value + expires +"; path=/";
	},
	read : function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	},
	erase : function(name) {
		this.create(name,"",-1);
	},
	/**
	*	transforms a 2D array into string format:
	*	input : [[name,uri],[name,uri]]
	*	output: name$$uri**name$$uri
	**/
	arrayToString : function(arr){
		var arr1 = [], arr2 = [];

		for( var i = 0; i < arr.length; i++ ){
			arr1.push( arr[i].join('$$') );
		}

		arr2.push( arr1.join('**') );
		return( arr2 += '' );
	},
	stringToArray : function (string){
		var arr = [];

		arr1 = string.split('**');

		for( var i = 0; i < arr1.length; i++ ){
			arr.push( arr1[i].split('$$') );
		}
		
		return( arr );
	}
}

function collectGeneralStats(){
	var info = j$('#wideResults > div.info div.mainText');
	var news = j$('#wideResults > div.news div.article');
	var relatedArticles = j$('#shortResults > div.relateditems');
	var posts = j$('#shortResults > div.blogs');
	var pics = j$('#shortResults > div.pics');

	var numOfArticles = news.length;
	var numOfPosts = posts.children('div.post').length;

	/*
	var numOfArticlesTopics = (function(){
		news.find('div.topics').each(function(){
			// need to count them for statistics
		});
	})();
	*/
	
	// bind related articles clicks
	news.delegate('a', 'mouseup', function () {
	    if (this.parentNode.nodeName.toUpperCase() == 'H3')
	        sendStat({ event: 'tp_article_click', name: escape(this.firstChild.nodeValue), link: escape(this.href) });
	    else {
	        sendStat({ event: 'tp_article_topic_click', name: escape(this.firstChild.nodeValue), link: escape(this.getAttribute('href')) });
	    }
	});

	// bind related blog posts clicks
	posts.delegate('a', 'mouseup', function(){
		sendStat({ event:'tp_post_click', name:escape(this.firstChild.nodeValue), link: escape(this.href) });
	});

	// bind related topics clicks
	relatedArticles.delegate('a', 'mouseup', function(){
        sendStat({ event: 'tp_relatedtopic_click', name: escape(this.firstChild.nodeValue), link: escape(this.href) });
	});
	
	// bind photo clicks
	pics.delegate('a', 'mouseup', function(){
		var linkName = j$(this).parent('li').children('div.semantipop').children('a').text();
		sendStat({ event:'tp_photo_click', name:escape(linkName), link: escape(this.href) });
	});
	
	info.delegate('a', 'mouseup', function(){
		var uri = gup2(); // like substr(30), but only on links which contains URIs
		sendStat({ event:'tp_info_link', name:escape(this.firstChild.nodeValue), link:uri });
	});
	
	j$('#header div.row2 ul.social a.addthis_button_email').click(function(){
		sendStat({ event:'tpShare', service:'email' });
	});
	
	j$('#addThisWidget div.services').delegate('a', 'mouseup', function() { 
		sendStat({ event:'tpShare', service:this.className });
	});
	
	// send 'topic page view' stat
	sendStat({ event:'tpv', articles:numOfArticles, posts:numOfPosts, referrer: (getReferrer() || 'null') });
}

// method to check for 'onbeforeunload' support
var el = document.createElement('div');
el.setAttribute('onbeforeunload', '');
if( typeof el.onbeforeunload == 'function' ){
	window.onbeforeunload = function(){
		sendStat({ event:'tp_out' });
	}
}

function generateGuid(){
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, 
		function(c) {
			var r = Math.random()*16|0,v=c=='x'?r:r&0x3|0x8;return v.toString(16);
			}).toLowerCase();
	//function S4(){
	  // return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
	//}
	//return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

horizon.userGuid = (function(){
	var guid = cookies.read('headup-user-guid');
	if(guid)
		return guid;
	else{
		guid = generateGuid();
		cookies.create("headup-user-guid", guid, 365);
		return guid;
	}
})();

function sendStat(statsJSON){
	var url = [];
	// Serializes an object
	url.push( j$.param(statsJSON) );
	url.push('&customerId=' + horizon.configid);
	url.push('&sessionId=' + horizon.sessionId);
	url.push('&userId=' + horizon.userGuid);
	var uri = horizon.uri.replace('http://schemas.semantinet.com/','');
	url.push('&uri=' + uri);
	url.push('&timeStamp=');
	url.push( new Date().getTime() );
	
	var stat = new Image();
	stat.src = horizon.path + 'headupStats.gif?' + url.join("");
}

function initShare(link){
	var short_url = '',
		link 	  = link || document.location.href,
		title	  = document.title;

	// Facebook 'like' button
//	j$('#header ul.social').children('li.fb_like').html('<iframe src="http://www.facebook.com/plugins/like.php?href='+ link +'%2Fpage%2Fto%2Flike&amp;layout=button_count&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:70px; height:21px;" allowTransparency="true"></iframe>');
		
	while( link.lastIndexOf("/") == (link.length-1) ){
		link = link.substring(0, link.length-1);
	}

	//var shortner = "http://ggl-shortener.appspot.com/?url=" + encodeURIComponent(window.location.href) + "&jsonp=urlShort_callback";
	var shortner = "http://api.bit.ly/v3/shorten?login=semantinet&apiKey=R_ca79d5e178a68004126a8619fd725dd9&uri=" + encodeURIComponent(link) +"&format=json&callback=urlShort_callback";
	j$.getScript(shortner);

	window.urlShort_callback = function(response){
		//if( response.error_message )
		//	console.log("An error occured: " + response.error_message);
		if( response.status_code == 200 )
			short_url = response.data.url;
			
		var source = short_url || encodeURI(link);
			//link_mail = source.replace( /&amp;|&+/g, '%26' ).replace(' ','%20');

		//j$('#header a.email').attr('href','mailto:?subject='+ title +'&body=Check out this great link:%0A%0a'+ encodeURI(link_mail) +'%0A%0adiscovered via @Headup');
		makeLinks(source);
	};

	function makeLinks(source){
		j$("#addThisWidget div.services a").attr('target','_blank').each(function(){
			var serviceName = this.className;
			if( this.className == 'twitter')
				this.href = "http://twitter.com/home?status="+ title +" - "+ source;
			
			else if( this.className == 'digg')
				this.href = "//www.addthis.com/bookmark.php?s="+ serviceName +"&url="+ link +"&title="+ title;
			
			else if( this.className == 'stumbleupon')
				this.href = "//www.addthis.com/bookmark.php?s="+ serviceName +"&url="+ link +"&title="+ title;
			
			else{
				this.href = "//www.addthis.com/bookmark.php?s="+ serviceName +"&url="+ source +"&title="+ title;
			}
		});
	}
}

var shareWidget = {
	overlay : j$('#overlay'),
	overlayExisted : false,
	close : function(){
		var that = this;
		j$("#addThisWidget").fadeOut(200, function(){ end() });
		function end(){
			that.overlay.css('z-index',99);
			if( !that.overlayExisted )
				that.overlay.fadeOut(150).unbind('click');
		}
		return false;
	},
	open : function(){
		var that = this;
		if( that.overlay.is(':visible') ){
			that.overlayExisted = true;
			that.overlay.css('z-index',999);
			j$("#addThisWidget").center().fadeIn(230);
		}
		else{
			that.overlay.fadeTo(150,0.3, function(){
				j$("#addThisWidget").center().fadeIn(230);
			});
			that.overlay.bind('click',function(){ that.close() });
		}
		return false;
	}
};

j$("#header a.share").bind('click', function(){
	// call 'initShare' to re-build the share links, init the links first time only if someone clicked the 'share' button
	if( !horizon.initShare )
		initShare();
	horizon.initShare = true;
	return shareWidget.open();
});

j$("#addThisWidget div.header a.close").bind('click', function(){
	return shareWidget.close();
});

watchVideoBind();

//-----------------------------------------------------
//	SemantiPop - manage related semantic popup stuff
//-----------------------------------------------------
function initSemantipop(){
	var timer=null, 
		element=null, 
		pos='50%', 
		width, 
		minWidth=178;
	
	// the elemnt which on hover should show the popup
	j$('#headupcontent .hasExtraData').live('mouseenter', function(){
		var that = this;
		// Sort of a delay. A timer is triggered on mouseleave, and if user come back to the same element before the timeout ends, clear it.
		clearTimeout(timer);
		// checks on every mouseeneter if event was triggered on the same element or a different one, then stores refferens to 'element'.
		if( that == element )
			return false;
		if( element ) // if one open, close it.
			closePopup();
		
		element = that;
		
		// binds mousemove event so get the exact mouse position from it, 
		// so the popup will be showed directly above it.
		
		//j$(element).bind('mousemove',function(event){ trackMousePos(event) });
		
		var semantipop = j$(this).children('div.semantipop');
		timer = setTimeout(function(){ showPopup(); }, 300);
	}).live('mouseleave', function(){
		j$(element).unbind('mousemove').find('a').removeAttr('style');
		clearTimeout(timer);
		timer = setTimeout(function(){ closePopup(); }, 250);
	});
	
	// calculate where, according to mouse position, should the popup be opened
	function trackMousePos(event){
		var target = event.srcElement;
		if (target == null)
			target = event.target;
		
		if( !j$(target).hasClass('hasExtraData') )
			target = j$(target).parents('.hasExtraData');
	
		var linkLeft = j$(target).offset().left;
		var linkWidth = target.offsetWidth;

		var pageX = event.pageX;
		pos = pageX - linkLeft;
	}
	
	function showPopup(){
		var semantipop = j$(element).children('div.semantipop');
		j$(element).find('span:first').css({position:'relative','z-index':2});
		var itemsCount = semantipop.find('ul > li').length;
		
		width = 0;
		if( itemsCount > 6 && itemsCount < 13 )
			width = Math.ceil( itemsCount/2 ) * (52 + 9);
		else
			width = itemsCount * (52 + 9); // number of items * (width of item + padding + 1px margin-left)
		
		if(width < minWidth)
			width = minWidth;

		var margin_left = -(width + 8)/2;
		semantipop.stop().removeAttr('style').css({bottom:20, left:pos, width:width, marginLeft:margin_left}).animate({opacity:'show', bottom:35},160);
		hooks.trigger('semantipopup', element);
	}
	
	function closePopup(){ // cleanup
		var semantipop = j$(element).unbind('mousemove').children('div.semantipop');
		semantipop.stop().animate({opacity:'hide'},100);
		semantipop.children('span').empty();
		element = null; 
	}
	
	// Bind event to the thumbnail hover to see it's name
	j$('ul li .semantipopitem', 'div.semantipop').live('mouseover', function(){
		var itemName = j$(this).attr('rel') || "";
		var nameContainer = j$(this).parents('div.semantipop').children('span');
		var maxLength = width > 220 ? 50 : 35;
		itemName = itemName.length > maxLength ? itemName.substring(0, maxLength) + "&hellip;" : itemName;
		nameContainer.html( itemName );
	}).live('mouseout', function(){
		j$(this).parents('div.semantipop').children('span').html('');
	});
};

function initSemantipopJP(){
	var timer = null, element = null, pos = 0;
	j$('#headupcontent .hasExtraData, #shortResults > div.pics ul.pics > li')
		.live('mouseenter', semantipopHover)
		.live('mouseleave', semantipopOut);

// Hover
	function semantipopHover(){
		var that = this;
		// Sort of a delay. A timer is triggered on mouseleave, and if user come back to the same element before the timeout ends, clear it.
		clearTimeout(timer);
		if( that == element ){
			return false;
		}
		if( element )
			closePopup();

		element = that;

		// binds mousemove event so get the exact mouse position from it, 
		// so the popup will be showed directly above it.
		if( j$(that).hasClass('hasExtraData') )
			j$(element).bind('mousemove',function(event){ trackMousePos(event) });

		var semantipop = j$(this).children('div.semantipop');
		timer = setTimeout(function(){ showPopup(); }, 300);
	}
	
// out
	function semantipopOut(){
		j$(element).unbind('mousemove').find('a').removeAttr('style');
		clearTimeout(timer);
		timer = setTimeout(function(){ closePopup(); }, 250);
	}
	
// trackMousePos
	function trackMousePos(event){
		var target = event.srcElement;
		if (target == null)
			target = event.target;

		if( !j$(target).hasClass('hasExtraData') )
			target = j$(target).parents('.hasExtraData');

		var linkLeft = j$(target).offset().left;
		var linkWidth = target.offsetWidth;

		var pageX = event.pageX;
		pos = pageX - linkLeft;
	}
	
	function showPopup(){
		var semantipop = j$(element).children('div.semantipop');
		
		semantipop.stop().removeAttr('style').css({bottom:22, left:pos, width:0, marginLeft:0}).animate({opacity:'show', bottom:38},160);
	}
	
	function closePopup(){
		var semantipop = j$(element).children('div.semantipop');
		semantipop.stop().animate({opacity:'hide'},100);
		//semantipop.children('span').empty();
		element = null;
	}

	// Bind event to the thumbnail hover
	j$('ul li a', 'div.semantipop').live('mouseover', function(){
		var itemName = j$(this).attr('rel') || "";
		var nameContainer = j$(this).parents('div.semantipop').children('span');
		itemName = itemName.length > 35 ? itemName.substring(0, 35) + "&hellip;" : itemName;
		nameContainer.html( itemName );
	}).live('mouseout', function(){
		j$(this).parents('div.semantipop').children('div').html('');
	});
};

function pager(){ 
	this.el = j$('<ul class="pager unselectable"/>').append('<li class="prev disabled">Prev</li>');
	
	this.active;
	this.first;
	this.pagerSize = 0;
	this.page = 1; // index of current page

	this.add = function(index){
		var li = jQuery('<li>'+ index +'</li>').data('page',index);
		this.el.append(li);
	}

	this.init = function (pages, callback) {
	    var context = this;
	    var listElements = this.el.find('li');
	    var first = this.el.find('li:first'); // first button
	    var last = this.el.find('li:last'); // last button
	    var gotoPage = null;
	    this.pages = pages;

	    listElements.eq(1).attr('class', 'active'); // reset first button
	    this.pagerSize = listElements.length - 2; // total buttons count excluding next & prev

	    this.el.delegate('li', 'click', function () {

	    	context.page = parseInt(window.location.hash.substring(1) || 1);
	    	var _maxSize = jQuery('.articles > div ').length;

	    	var $li = jQuery(this);

	    	if ($li.hasClass('disabled') || this.className == 'active')
	    		return;

	    	//pages.eq(context.page - 1).hide(); // hide the last seen page

	    	if ($li.hasClass('prev'))
	    		gotoPage = (context.page == 1) ? 1 : context.page - 1;

	    	else if ($li.hasClass('next'))
	    		gotoPage = (context.page == _maxSize) ? _maxSize : context.page + 1;

	    	else
	    		gotoPage = $li.data('page');


	    	// check to toggle next/prev
	    	//context.page > 1 ? first.removeClass('disabled') : first.addClass('disabled');
	    	//context.page < context.pagerSize ? last.removeClass('disabled') : last.addClass('disabled');
	    	// change the page and paint the button

	    	//listElements.eq(context.page).attr('class', 'active').siblings('li.active').removeAttr('class');
	    	//pages.eq(context.page - 1).css('display', 'block');

	    	if (callback)
	    		callback.call({ page: gotoPage });

	    	window.document.location.hash = gotoPage;
	    	window.location.reload();

	    });

	    _pageFromUrl = window.location.hash.substring(1) || null;
	    if (_pageFromUrl && _pageFromUrl != 1) {

	        //pages.eq(_pageFromUrl - 1).hide(); // hide the last seen page
	        articlePages = j$('div.articles > div');
	        // hide all other pages
			articlePages.hide();
	        // show the current page
	        //j$(articlePages[_pageFromUrl - 1]).show();

	        // check to toggle next/prev
	        _pageFromUrl > 1 ? first.removeClass('disabled') : first.addClass('disabled');
	        _pageFromUrl < context.pagerSize ? last.removeClass('disabled') : last.addClass('disabled');
	        // change the page and paint the button

	        listElements.eq(_pageFromUrl).attr('class', 'active').siblings('li.active').removeAttr('class');
	        pages.eq(_pageFromUrl -1).css('display', 'block');
	    }
	    //j$('.articles').show();
	}
}

/*
	title	- widget's title
	dom		- jquery object of the dom object being manipulated
*/
function proccessWidget(title, dom){
	switch( title ){
		case 'info' :
			limitInfo(dom);
			break;
		case 'mutualentities' :
			break;	
		case 'news' :
			proccessNews( dom.find('div.articles') );
			break;
		case 'blogs' :
			if( !dom.find('div.post').length )
			    dom.append('<p class="noData">No related posts</p>');
			break;
		case 'pics' :
			if( !dom.find('ul.pics li').length ){
				dom.remove();
				return false;
			}
			else{
				//initSemantipop();
				dom.hide();  // hide the pics widget before proccesing it
				// this happens async
				proccessPics( dom );
				// check again, after 'proccessPics', if there are any List Items left
				if( !dom.find('ul.pics li').length ){
					dom.remove();
					return false;
				}
			}
			break;
		case 'relateditems' :
			if( !dom.find('ul li').length ){
				dom.remove();
				return false;
			}
			break;
		case 'photogallery' :
			dom.prepend('<h2 class="title">Photos</h2>');
			//dom.find("div.ad-gallery").addClass('loading');
			break;
		case 'videos' :
			dom.prepend('<h2 class="title">Videos</h2>');
			//dom.find("div.ad-gallery").addClass('loading');
			break;	
		case 'films' :
			dom.prepend('<h2 class="title">Films</h2>');
			//dom.find("div.ad-gallery").addClass('loading');
			break;			
		case 'tweets' :
			dom.prepend('<h2 class="title tweets floatl">Tweets<b></b></h2>');
			dom = limitTweets(dom);
			break;			
	}
	
	// show the widgets (after manipulation is done)
	dom.show();
}

function limitTweets(html){
	var $twts = html.find('span.moduleType3');
	// if more than 4 tweets, trim them and show the button
	if( $twts.length > 4 ){
		var hiddenTweets = $twts.slice(4).hide();  // hide all Tweets after the 4th one
		var moreBtn = j$('<a class="btn">Show all</a>');
		html.prepend(moreBtn);
		moreBtn.click(function(){
			j$(this).remove();
			hiddenTweets.each(function(i){
				j$(this).delay(i * 200).fadeIn(200); // show Tweets one by one by creating a delay between them
			});
		});
	}
	return html;
}
function limitInfo(widget){
	var textCont = widget.find('div.mainText');
	var allText = textCont.text();
	var toggler = widget.find('a').attr('target','_blank');
	
	toggler.bind('mouseup', function(){
		sendStat({ event:'expand_info', action:escape(toggler.text()) });
	});

	if( allText.length > 900 ){
		// if text is too long, change link text to 'read more' and bind a function to it that will trigger only once when clicked
		toggler.text('Read more').one('click', function(){
			textCont.addClass('long');
			toggler.text('Read all');
			return false;
		});
		
		// trim text
		var maxChars = 600;
		// make sure text is not beeing trimmed in bad places, like after a space, dot or comma
		for( var i=0; i < allText.length; i++ ){
			if( /(,|\.| )/.test(allText.charAt(maxChars-1)) ) --maxChars;
			else break;
		}
		
		// split the long text to 2 seperate containers
		var shortText = allText.substring(0, maxChars) + "<span class='hellip'>&hellip;</span>";
		var LongText = allText.substring(maxChars, allText.length);
		
		var shortTextParagraph = j$('<p/>').html(shortText);
		var LongTextParagraph = j$('<p/>').html(LongText);

		textCont.find('p').remove().end().append(shortTextParagraph).append(LongTextParagraph);
	}

	// replace main image with placeholder is dead
//	var mainImage = textCont.children('img.mainImage');
//	if( !mainImage.length )
//		textCont.prepend('<img src="images_jpost/maintext_placeholder_info.png" alt="" class="mainImage placeholder" />');
}

function proccessNews(widget){
	var title = widget.children('h2');
	var articles = widget.children('div.article');
	var section_size = 5;
	// includes the related articles count num to the title
	if( !articles.length ){
		return false;
	}
	
	title.find('span')[0].innerHTML += ' ('+ articles.length +')';

	var articles_arr = j$.makeArray(articles);

	// splits the artiles into sections of fives, and assign paging if there is minimum 'section_size' articles 
	if( articles_arr.length > section_size ){
		// creates the Pager element
		var articlesPager = new pager();
		//var midAd = document.getElementById('ads.mid.1');

		for(var i=0,j=1; i < articles_arr.length; i+=section_size, j++){
		
			articlesPager.add(j);
			var wrapper = j$('<div/>');//.addClass('page_' + j);
			wrapper.hide();
			var part = articles_arr.slice(i,i+section_size);

			// append each of 'section_size' items to the wrapper element, then append each wrapper to the 'widget' element
			for(var k=0; k < part.length; k++){
				// trim text in articles
				/*
				var orginalText = j$(part[x]).find("div.text p");
				var newText = orginalText.text().substr(0,150);
				newText = newText + "&hellip;";
				orginalText.html(newText);
				*/
//				if( k==2 || part.length < 2 )
//					wrapper.append('<div class="midAdCont" />');
				wrapper.append(part[k]);
			}
			widget.append(wrapper);

			// Show the first set of Articles and copy the Ad to the right place, and show it
			if( j==1 ){
				wrapper.css('display','block');
				// check that the AD has loaded before moving it inside the DOM
				var AdTimerCount = 25;
				var adPlaceholder = wrapper.find('div.midAdCont')[0];
				
				if (adPlaceholder){
					var appendMidAdTimer = setInterval(function(){
						if( midAd.getAttribute('dcstatus') == 'loaded' ){
							adPlaceholder.appendChild(midAd); // moves the AD to the right place
							midAd.style.height = 'auto';
							clearInterval(appendMidAdTimer);
						} else if( --AdTimerCount == 0 )
							clearInterval(appendMidAdTimer);
					}, 500);
				};
			}
		}

		function articlesPagerClick(){
			sendStat({ event:'articles_pager_click', targetPage: this.page });
		}

		articlesPager.el.append('<li class="next">Next</li>').appendTo(widget);
		articlesPager.init( widget.children('div'), articlesPagerClick );
		
		//articlesPager.el.clone(true).insertAfter(title);
	}
}

function watchVideoBind(){
	var btn = j$('button.triggerVideo')
	if(btn){
		btn.live('click',function(){
			var video_json = j$.parseJSON( j$(this).attr('rel') );
			var extVideo = new hgb();
			var videoTitle = video_json.Caption.length > 75 ? video_json.Caption.substring(0, 75) + "&hellip;" : video_json.Caption;
			var video_html = unescape( video_json.displayHtml );
			extVideo.buildVideoPlayer( video_html );
			extVideo.loadMovie( videoTitle, video_html );
			extVideo.showModal();
		});
	}
}

// kill dead image's list items
function proccessPics(widget){
	var picsList = widget.find('ul.pics').hide();
	var images = widget.find('ul.pics li img');
	var imagesCount = images.length;
	images.each(function(i){
            var that = this, 
				pic = new Image();
            pic.onload = function(){
                pic.onload = null;
                if( !--imagesCount ) // if done with all images
                    handlePics();
            }
            pic.onerror = function(){
				pic.onerror = null;
				j$(that).parents('li').remove();
                if( !--imagesCount ) // if done with all images
                    handlePics();
            }
            pic.src = this.src;
	});

	function handlePics(){
		var newCount = picsList.find('li').length;
		var remainder = newCount % 3;
		if( remainder ){
			for( var i=0; i < remainder; i++){
				picsList.find('li:last').remove();
			}
		}
		picsList.show();
	}
}



// init the widgets
j$(document).ready(function(){
	initSemantipop();
	horizon.widgets = j$('div.headupwidget');
	horizon.widgets.each(function(){
		var title = this.className.split(' ')[1];
		proccessWidget( title, j$(this) );
	});
	InitFriendsLiteModule(); // init facebook connect
	collectGeneralStats();
	// init event listeners
	// carusel
	j$('#itemcarousel .ad-forward').bind('mouseup', function(){ sendStat({event: 'caruselScrollRight'}) } );
	j$('#itemcarousel .ad-back').bind('mouseup', function(){ sendStat({event: 'caruselScrollLeft'}) });
	j$('#itemcarousel .ad-thumb-list').delegate('li', 'mouseup', function(event){  
		sendStat({ 
			event: 'caruselMovieClick',
			link: j$(this).find('.clickable').data('link'),
			name: j$(this).find('small').text()
		})
	});
	
	hooks.hookTo('semantipopup', function(item) { sendStat({event: 'workedWithPopUp', name: j$(item).find('.mutualname').text()}) } );
	
	// worked with
	j$('.entitiesList').delegate('.semantipop  .semantipopitem', 'mouseup', function(item) {
		sendStat({ 
			event: 'workedWithMovieClick',
			link: j$(this).find('a').attr('href'),
			name: gup2(),
			workedWithName: j$(this).parents('.hasExtraData').find('.mutualname').find('span').text()
		})
	});
	j$('.mutualname').bind('mouseup', function(event){ 
		sendStat({ 
			event: 'workedWithPersonClick',
			link: j$(this).find('a').attr('href'),
			name: gup2(),
			workedWithName: j$(this).find('span').text()
		})
	});
	// photos
	
	j$('#photogallery').delegate('li', 'mousedown', function() { 
		sendStat({ 
			event: 'photoGalleryClick',
			name: j$(this).find('img').attr('alt'),
			link: j$(this).find('a').attr('href'),
		})
	});
	
	// fancy box
	j$('#fancybox-left, #fancybox-right').bind('mousedown', function(){
		sendStat({ 
			event: 'photoGalleryFancyBox',
			name: j$('#fancybox-title a').text(),
			link: j$('#fancybox-img').attr('src'),
		})
	});
	// videos
	j$('#videogallery').find('.ad-thumb-list').delegate('li', 'mousedown', function() { 
		sendStat({ 
			event: 'videoClick',
			name: j$(this).find('a').attr('title'),
			link: j$(this).data('link'),
		})
	});
	
	// for the movie page
	j$('#wideResults').find('.triggerVideo').bind('mouseup', function(){ 
		sendStat({ 
			event: 'trailerClick'
		})
	});
	j$('#wideResults').find('.amazon').bind('mouseup', function(){ 
		sendStat({ 
			event: 'amazonClick'
		})
	});
	j$('#wideResults').find('.val a').bind('mouseup', function(){ 
		sendStat({ 
			event: 'websiteClick'
		})
	});
	
});

function fixPeaceTalks2010(){
	var uri = gup2();
	if(uri == "Peace_Talks_2010" || uri == "General_Assembly_2010"){
		var favicon = j$('img.favicon');
		var parent = favicon[0].parentNode;
		parent.removeChild(parent.childNodes[7]);
		parent.removeChild(parent.childNodes[2]);
		parent.removeChild(parent.childNodes[1]);
	}
}
fixPeaceTalks2010();

