/**
 * This file requires dynamic object in background.js.jspx or background.js.jsp 
**/

var holder = new Holder();
var myPubs, bundle;
var context = dynamic['ctx'];
var fullContext = dynamic['fullCtx'];

//#{ctx}/js/map.js
function Holder() {	
	this.newspapers = {};
	this.newspaperMap=new Map;
}

Holder.prototype.addNewspaper = function(newspaper) {
	this.newspapers[ newspaper.id ] = newspaper;
	this.newspaperMap.put(newspaper.id, newspaper);
	return this;
}

function Newspaper(
		 id,
		 docDate,
		 pubId,
		 pubName,
		 pubDisplayName,
		 thumbUrl,
		 type, 
		 locality, 
		 region,
		 city,
		 status,
		 product,
		 period,
		 currPrice,
		 headlineId,
		 pathPrefix) {
	this.clips = {};
	this.setId(id).setDocDate(docDate).setPubId(pubId).setPubName(pubName).setPubDisplayName(pubDisplayName)
		.setThumbUrl(thumbUrl).setType(type).setLocality(locality).setRegion(region).setCity(city).setStatus(status)
		.setProduct(product).setPeriod(period).setCurrPrice(currPrice).setHeadlineId(headlineId).setPathPrefix(pathPrefix);
		
}

Newspaper.prototype = {
		setId : function(id) { 
			this.id = id; return this; 
		},
		setDocDate : function(docDate) { 
			this.docDate = docDate; return this; 
		},
		setMyPubBeginDate : function(myPubBeginDate) { 
			this.myPubBeginDate = myPubBeginDate; return this; 
		},
		setMyPubEndDate : function(myPubEndDate) { 
			this.myPubEndDate = myPubEndDate; return this; 
		},
		setRemainingTime : function(remainingTime) { 
			this.remainingTime = remainingTime; return this; 
		},
		setPubId : function(pubId) { 
			this.pubId = pubId; return this; 
		},
		setPubName : function(pubName) { 
			this.pubName = pubName; return this; 
		},
		setPubDisplayName : function(pubDisplayName) { 
			this.pubDisplayName = pubDisplayName; return this; 
		},
		setThumbUrl : function(thumbUrl) { 
			this._thumbUrl = thumbUrl; 
			return this;
		},
		getRemainingTime : function() { 
			return this.remainingTime;
		},
		getMyPubBeginDate : function() { 
			return this.myPubBeginDate; 
		},
		getMyPubEndDate : function() { 
			return this.myPubEndDate; 
		},
		getPubId:function(){
			return this.pubId;
		},	
		getThumbUrl : function() {
			return this._thumbUrl;
		},
		getMediumThumbUrl : function() {
			return this._thumbUrl + "_medium.jpeg";
		},
		getSmallThumbUrl : function() {
			return this._thumbUrl + "_small.jpeg";
		},
		getFpThumbUrl : function() {
			return this._thumbUrl.replace(/_thumbnail\.jpeg/, "_fp.jpeg");
		},
		getCurrPrice : function () {
			return this.currPrice;
		},
		getRegion : function () {
			return this.region;
		},
		setType : function(type) { 
			this.type = type; return this; 
		},
		setLocality : function(locality) { 
			this.locality = locality; return this; 
		},
		setRegion : function(region) { 
			this.region = region; return this; 
		},
		setCity : function(city) { 
			this.city = city; return this; 
		},
		setStatus : function(status) { 
			this.status = status; return this; 
		},
		setProduct : function(product) { 
			this.product = product; 
			this.priceList = getPriceList( this.product.prices, bundle['pub_price'], bundle['pub_real_price'] );
			return this; 
		},
		setPeriod : function(period) { 
			this.period = period; return this; 
		},
		setCurrPrice : function(currPrice) {
			this.currPrice = currPrice; return this;
		},
		setHeadlineId : function(headlineId) { 
			this.headlineId = headlineId; return this; 
		},
		setPathPrefix : function(pathPrefix) { 
			this.pathPrefix = pathPrefix; return this; 
		},
		
		addClip : function(clip) { 
			this.clips[clip.id] = clip;
			clip.setNewspaper(this); 
			return this; 
		}
};
Newspaper.prototype.constructor = Newspaper;

function Clip(
		id,
		title,
		summary,
		section,
		newsType,
		image,
		article ) {
	this.newspaper = null;
	this.setId(id).setTitle(title).setSummary(summary).setSection(section).setNewsType(newsType).setImage(image).setArticle(article);
}

Clip.prototype = {
		setId : function(id) { 
			this.id = id; return this; 
		},
		setTitle : function(title) { 
			this.title = title; return this; 
		},
		setSummary : function(summary) { 
			this.summary = summary; return this; 
		},
		setSection : function(section) { 
			this.section = section; return this; 
		},
		setNewsType : function(newsType) { 
			this.newsType = newsType; return this; 
		},
		setImage : function(image) { 
			this._image = image; return this;
		},
		setArticle : function(article) { 
			this.article = article; return this; 
		},
		setNewspaper : function(newspaper) { 
			this.newspaper = newspaper; return this;
		},
		getClipUrl : function() {
			return this.newspaper.pathPrefix + this._image + '_clip.jpeg';
		},
		getInpageUrl : function() {
			return this.newspaper.pathPrefix + this._image + '_thumbnail.jpeg';
		}
};

Clip.prototype.constructor = Clip;
	
function isMypub(pubId) {
	return myPubs && myPubs[pubId];
}

function goDemoNews(pubId){
	
	var params = {};
	if(pubId <= 0)
		return;
	
	params.pubId = pubId;
	params.demo = 'true';
	postParams(context + "/rjreader/",params);
}

function searchPub(pubName){
	
	var params = {};
	if(pubName == '')
		return;
	
	params.pubName = pubName;
	params.destroy_bean = "searchBean";
	postParams(context + "/search/",params);
}

function openSign(newspaperId, contour) {
	var params = {};
	if(newspaperId>0)
		params.publisher = holder.newspapers[newspaperId].pubName;
	if(contour!=undefined)
		params.type = "contour";
	
	params.back = context+"/monitor/";
	params.destroy_bean = "signup";
	postParams(context + "/secure/sign/", params);
} 

function openDaily(newspaperId) {
	var params = {};
	params.publisher = holder.newspapers[newspaperId].pubName;
	postParams(context + "/daily/", params);
}

function openPapir(newspaperId, clipId) {
	var news = holder.newspapers[newspaperId];
	var params = {};
	params.publisher = news.pubName;
	params.docNo = news.id;
	params.home = fullContext+"/monitor/";
	if( clipId )
		params.clipId = clipId;
	postParams(context + "/rjreader/", params);
}

function openClipSearch(newspaperId) {
	var params = {};
	params.pub = holder.newspapers[newspaperId].pubName;
	params.t = "c";
	params.back = context+"/monitor/";
	params.destroy_bean = "searchBean";
	postParams(context + "/search/", params);
}

function createContentSlider() {
	for(var id in holder.newspapers) {
		document.write(ccs(id));
	}
}

function ccs(id){
	var news = holder.newspapers[id];
	var html = '<div class="contentdiv">';
	var url = dynamic['ctx']+ '/daily_archive/daily_paper.swf';
	var params = {};	
	var searchLabel = bundle['search'].replace('{0}',news.pubDisplayName);
	html += "<table class='ack'><tr>";
	
	html += "<td >";
	html += "<div class='newspaper_img' onclick='imageClicked(this); return false;' id='newspaper_img_"+news.id+"' style='margin-right: 8px'>";
	html += "<a href='javascript:;'>";
	html += "<img src='" + news.getMediumThumbUrl() +"' border='0px' />";
	html += "</a>";
	html += "</div>";
	html += "<br/>";
	html += "</td >";
	html += "<td >";
	html += "<div >";
	html += "<span style='font-size:14pt; font-weight:bold;'>" + news.pubDisplayName  +" Gazetesi</span>";
	html += "<br/>";
	html += "<span style='font-size:9pt; font-weight:bold;'>" + news.region +" - "+news.city + "</span>";
	html += "<br/>";
	html += "<span style='font-size:12pt; font-weight:bold;'>" + news.docDate + "</span>";
	html += "<br/>";
	html += "<br/>";
	html += "<span style='font-size:10pt; font-weight:bold;'>" + news.currPrice + " TL</span>";
	html += "<br/>";
	html += "<br/>";
	/*
	html += '<a id="demo_href" class="link" style="font-size: 10pt" href="#" onclick="goDemoNews('+ news.pubId +')">';
	html += '<img src="/image/arrow_right.gif" style="margin-right: 5px" />';
	html += bundle['demo'];
	html += "</a>";
	html += "<br/>";
	*/
	html += '<a id="search_href" class="link" style="font-size: 10pt" href="#" onclick="searchPub(\'' + news.pubName + '\')">';
	html += '<img src="/image/arrow_right.gif" style="margin-right: 5px" />';
	html += searchLabel;
	html += "</a>";
	html += "<br/>";
	html += '<img src="/image/arrow_right.gif" style="margin-right: 5px" />';
	html += "<a href='javascript:;' class='link' style='font-size: 10pt' onclick='openDaily("+news.id+"); return false' >" + news.pubDisplayName + " Market</a>";
	html += "<br/>";
	html += "</div >";
	html += "</td>";	

	html += "</tr></table>";
	html += '</div>';
	return html;
}

function dateDifference(endDate,beginDate){
	var one_day=1000*60*60;
	return Math.ceil((endDate.getTime()-beginDate.getTime())/(one_day));
}

function myPubsInfo(id,state){
	
	//0->ac and time>2 day 1->time<=2 day
	var news = holder.newspapers[id];
	var html = '<div class="contentdiv">';
	var url = dynamic['ctx']+ '/daily_archive/daily_paper.swf';
	var params = {};	
	var searchLabel = bundle['search'].replace('{0}',news.pubDisplayName);
	html += "<table class='ack'><tr>";
	
	html += "<td >";
	html += "<div class='newspaper_img' onclick='imageClicked(this); return false;' id='newspaper_img_"+news.id+"' style='margin-right: 8px'>";
	html += "<a href='javascript:;'>";
	html += "<img src='" + news.getMediumThumbUrl() +"' border='0px' />";
	html += "</a>";
	html += "</div>";
	html += "<br/>";
	html += "</td >";
	html += "<td >";
	html += "<div >";
	html += "<span style='font-size:14pt; font-weight:bold;'>" + news.pubDisplayName  +" Gazetesi</span>";
	html += "<br/>";
	html += "<span style='font-size:9pt; font-weight:bold;'>" + news.region +" - "+news.city + "</span>";
	html += "<br/>";
	html += "<span style='font-size:12pt; font-weight:bold;'>" + news.docDate + "</span>";
	html += "<br/>";
	html += "<br/>"; 
	html += "<span style='font-size:10pt; font-weight:bold;'>Abonelik Başlangıç Tarihiniz :" + news.getMyPubBeginDate() + "</span>";
	html += "<br/>";
	html += "<span style='font-size:10pt; font-weight:bold;'>Abonelik Bitiş Tarihiniz :" + news.getMyPubEndDate() + " </span>";
	html += "<br/>";
	/*
	html += '<a id="demo_href" class="link" style="font-size: 10pt" href="#" onclick="goDemoNews('+ news.pubId +')">';
	html += '<img src="/image/arrow_right.gif" style="margin-right: 5px" />';
	html += "Hemen Oku"
	html += "</a>";
	html += "<br/>";
	*/
	html += '<a id="search_href" class="link" style="font-size: 10pt" href="#" onclick="searchPub(\'' + news.pubName + '\')">';
	html += '<img src="/image/arrow_right.gif" style="margin-right: 5px" />';
	html += searchLabel;
	html += "</a>";
	html += "<br/>";
	html += '<img src="/image/arrow_right.gif" style="margin-right: 5px" />';
	html += "<a href='javascript:;' class='link' style='font-size: 10pt' onclick='openDaily("+news.id+"); return false' >" + news.pubDisplayName + " Market</a>";
	html += "<br/>";
	if(state==1){
		var postData="postForm('/secure/sign/','destroy_bean','signup','back', '/monitor','publisher','"+news.pubName+"')";
		 html+="<span style='font-size:10pt; font-weight:bold;'>Üyeliğinizin bitimine "
			 +news.getRemainingTime()+" saat kamıştır, " +
			 		"<a style='text-decoration:underline;cursor:pointer;' onclick=\""+postData+"\">Üyeliğinizi uzatmak için..</a></span>";
	}	
	html += "</div >";
	html += "</td>";	
	
	html += "</tr></table>";
	html += '</div>';
	return html;
}


function createArticleList() {
	document.write('<table cellspacing="0" align="center" width="95%">');
	for( var nid in holder.newspapers ) {
		var news = holder.newspapers[nid];
		var openPapirFunc = 'openPapir('+nid+')';
		for( var cid in news.clips ) {
			var clip = news.clips[cid];
			if( clip.article ) {
				var html = '<tr><td>';
				html += '<img src="/image/plus_small.png" onclick="showBody('+clip.id +')" id="a' + clip.id + '" ';
				html += 'style="'+(clip.summary ? '' : 'visibility:hidden')+'"/>';
				html += '<span class="pubname"  style="padding-left: 5px; font-weight:normal">'+ news.pubDisplayName +': </span> '; 
				html +=	'<span class="spanLink" style="font-weight:normal" onclick="'+openPapirFunc+'">' +	clip.title + '</span>';
				html += '<div id="div' + clip.id + '" style="display: none; padding-left: 15px;" class="newspaper_text">  '+clip.summary+'</div>';
				html += '</td></tr>';
				document.write(html);
			}
		}
	}
	document.write('</table>');
	plusImg = context + "/image/plus_small.png";
	minusImg = context + "/image/minus_small.png";
}

	var lastShowId;

function showBody(clipId) {
	var target = jq("#a"+clipId);
	var div = jq("#div"+clipId); 
	if( div.css('display')=='none' ) {
		target.attr("src", minusImg);
		if( lastShowId ) {
			jq("#div"+lastShowId).hide("slow");
			document.getElementById('a'+lastShowId).src = plusImg;
		}
		div.slideDown("slow");
		lastShowId = clipId;
	}
	else {
		target.attr("src", plusImg);
		div.slideUp("slow");
	} 
}

function createNewspaperPanel(params) {
	var table = "<table align='left' class='image_table'><tr>";
	for(var i in holder.newspapers) {
		var news = holder.newspapers[ i ];
		var display = true;
		for( var paramKey in params ) {
			var paramValue = params[paramKey];
			//if value is array, compare Newspaper property with all array elements
			//if not equals any of elements, not display anyting.
			if( paramValue instanceof Array ) {
				if( !existsInArray( paramValue, news[paramKey] ) ) {
					display = false; 
					break;
				}
			}
			else {
				if( paramValue!==news[paramKey] ) {
					display = false; 
					break;
				}
			}
			
		}
		if( display===true ) {
			table += "<td><div class='newspaper_img' >";
			table += "<a href='javascript:;' onclick='imageClicked(this); return false' id='newspaper_img_"+news.id+"'>";
			table += "<img src='" + news.getFpThumbUrl() +"' border='0px' />";
			table += "</a></div></td>";
		}
	}
	table += "</tr></table>";
	return table;
}

function getMyPubs(myPubs,header,container) {
		var map=holder.newspaperMap;
		var s="";
		/**
		 * ac : isActive
		 * ex : isExpired
		 * bd : beginDate
		 * ed : endDate
		 */
		var table = "<table align='left' class='image_table'>" +
		"<tr id='newsHeaderBlock'><th colspan='5'  style='white-space:nowrap;'>"+header+"</th></tr>";
		var p="";
		var count=0;
		for(var pid in myPubs){
			var productProperties=myPubs[pid];
			var news=null;
			var indis = 0;
			for( ;indis++ < map.size; map.next()){//map pointer
				var temp=map.value();
				if(temp.pubId==pid){
					temp.setMyPubBeginDate(productProperties["bd"]).setMyPubEndDate(productProperties["ed"]);
					news=temp;
				}
			}
			
			var ac=productProperties["ac"];
			var ex=productProperties["ex"];
			if(news==null||ex) continue;
			/*
			for(var key in productProperties){
				s+=key+":"+productProperties[key]+"\n";
				
			}*/
			
			if(count%5==0) {
				table+="<tr/>";
			}	
			++count;
			
			var bdate=productProperties["bd"];
			var edate=productProperties["ed"];
			var edatesplit=edate.split(".");
			var bdatesplit=bdate.split(".");
			var remaining=dateDifference(new Date(edatesplit[2],edatesplit[1]-1,edatesplit[0]),new Date());
			news.setRemainingTime(remaining);
			var state=(remaining>0&&remaining<=48) ? 1:0;
			table += "<td><div class='newspaper_img' >";
			table += "<a onclick='javascript:showNewspaperInfo("+news.id+","+state+")'>";
			table += "<img style='cursor:pointer;' src='" + news.getFpThumbUrl() 
			+"' border='0px' alt='"+ news.pubDisplayName +"' title='"+ news.pubDisplayName +"'/>";
			table+= "</a></div>";
			table+=showTooltip(news);
			table+="</td>";
		}
		table += "</table>";
		document.getElementById(container).innerHTML=table;
		if(count==0)document.getElementById('newsHeaderBlock').style.display='none';
	
		//alert(p);
		//if(count==0)document.getElementById('newsHeaderBlock').style.display='none';
}
function getNewspapers(params,header,container) {
	var table = "<table align='left' class='image_table'>" +
			"<tr id='newsHeaderBlock'><th colspan='5'  style='white-space:nowrap;'>"+header+"</th></tr>";
		var count=0;	
		var newspapers="";
		var map=holder.newspaperMap;
		for(var indis = 0; indis++ < map.size; map.next()){
		var news = map.value();
		var display = true;
		for( var paramKey in params ) {
			var paramValue = params[paramKey];
			if( paramValue instanceof Array ) {
				if( !existsInArray( paramValue, news[paramKey] ) ) {
					display = false; 
					break;
				}
			}
			else {
				if( paramValue!==news[paramKey] ) {
					display = false; 
					break;
				}
			}
			
		}
		if( display===true ) {
			if(count%5==0) {
				table+="<tr/>";
			}	
			table += "<td><div class='newspaper_img' tooltip=\"tool_"+news.id+"\">";
			table += "<a onclick='javascript:showNewspaperInfo("+news.id+",-1)'>";
			table += "<img style='cursor:pointer;' src='" + news.getFpThumbUrl() 
			+"' border='0px' alt='"+ news.pubDisplayName +"'/>";
			table += "</a></div>";
			table+=showTooltip(news);
			table+="</td>";
			++count;
		}
		
	}
	
	table += "</table>";
	document.getElementById(container).innerHTML=table;
	if(count==0)document.getElementById('newsHeaderBlock').style.display='none';
	map.removeAll; 
	return table;
}

function showTooltip(newspaper){
	var subtable="<div id=\"tool_"+newspaper.id+"\" style='display:none;'  >";
	subtable+="<div class='tooltip' title='ahmet'>";
	subtable+="<div class='header'>"+newspaper.pubDisplayName+"</div>";
	subtable+="<div class='date'>"+newspaper.region+" - "+newspaper.city+"</div>";
	subtable+="<div class='date'>"+newspaper.docDate+"</div>";
	subtable+="<div class='desc'>(Detayları görmek için Tıklayınız)</div>";
	subtable+="</div></div>";
	return subtable;
}

function showNewspaperInfo(newspaperId,myPubsState){
	var newspaper;
	if(newspaperId>0) newspaper = holder.newspapers[newspaperId];
	document.getElementById("slider1").innerHTML=myPubsState!=-1 ? myPubsInfo(newspaperId, myPubsState):ccs(newspaperId);
	window.location="#monitorSlider";
	//alert(ccs2(newspaperId));
}

function sfx(newspaper,myPubsState){
	
	document.getElementById("slider1").innerHTML=myPubsState!=-1 ? myPubsInfo(newspaper.id, myPubsState):ccs(newspaper.id);
	window.location="#monitorSlider";
	//alert(ccs2(newspaperId));
}


function showNewspaperPanel(params) {
	var mainDiv = jq("#newspaper_content_pane");
	mainDiv.hide().html( createNewspaperPanel(params) );
	mainDiv.show("slow");
}
function jsSleep(naptime){
	  naptime = naptime * 1000;
	  var sleeping = true;
	  var now = new Date();
	  var alarm;
	  var startingMSeconds = now.getTime();
	  
	  while(sleeping){
	  alarm = new Date();
	  alarmMSeconds = alarm.getTime();
	  if(alarmMSeconds - startingMSeconds > naptime){ sleeping = false; }
	} 
}	  

imageClicked = function(comp) {
	//if( selectedNewspaper ) {
	//	jq(selectedNewspaper).removeClass("selected_img");
	//}
	//jq(comp).addClass("selected_img");
	//selectedNewspaper = comp;
	
	var newspaperId =  comp.id.replace("newspaper_img_",""); 
	
	openPapir( parseInt(newspaperId) );
};

function existsInArray(array, value) {
	for(var ind in array)
		if( array[ind]==value )
			return true;
	return false;
}

function resizeRightDiv() {
	var newWidth = jq(window).width()*0.95;
	jq("#main_div").width(newWidth);
}

function createNewspaperMenu() {
	jq("#newspaper_header_pane a").click( function() {
		if( selectedMenu!=this ) {
			if( selectedMenu!=null && selectedMenu )
				jq(selectedMenu).removeClass("archive_menu_selected").addClass("archive_menu");
			jq(this).removeClass("archive_menu").addClass("archive_menu_selected");
			selectedMenu = this;
			//selectedNewspaper = null;
		}
		eval( "showNewspaperPanel(" + this.getAttribute("params") + ")" );
	} );
	//resizeRightDiv();
	
	if( undefined != selectedMenuId ) {
		selectedMenu = document.getElementById(selectedMenuId);
		selectedMenu.className = "archive_menu_selected"; 
		var func = "createNewspaperPanel(" + selectedMenu.getAttribute("params") + ")";
		var html = eval(func);
		document.getElementById("newspaper_content_pane").innerHTML = html;
	}
}

//jq(window).resize( resizeRightDiv );