var jFeed = jQuery.noConflict();
var Feeds = {
	isFeedComplete: false,
	Init		: function (pageowner_id, username, app_id, k,container,limit, notificationLimit) {
					this.PageOwnerId = pageowner_id;
					this.AppId 		 = app_id;
					this.k			 = k;
					this.PagingFeed  = new Paginator(limit);
					this.PagingNotification = new Paginator(notificationLimit);
					Layout.Container	 = container; 
					jFeed('#' + Layout.Container).css('background-color', '#FFF');
					this.Username = username;
					if (username != "" && (username == pageowner_id)) {
						Layout.showNotification = true;
					}else {
						Layout.showNotification = false;
					}
					Layout.GenerateLayout();
					
					//All variables are set,now get feeds !
					this.GetFeeds();
					if (Layout.showNotification == true) {
						Cookie.GetNotificationCountCookie();
						this.ShowNotificationCount();
					}
				},
	InitGeneralFeed: function(pageowner_id,app_id,k,container,limit) {
					this.CommentAllowed = false;
					this.PageOwnerId 	= pageowner_id;
					this.AppId 			= app_id;
					this.k				= k;
					Layout.Container 	= container;
					this.PagingGeneralFeed = new Paginator(limit);
					Layout.showNotification = false;
					Layout.GenerateLayout();
					this.GetGeneralFeeds();					
				},
	Username	: '',
	CurrentTab	: 'unread',
	PageOwnerId : '',
	PagingFeed	: '',
	PagingNotification : '',
	PagingGeneralFeed: '',
	AppId		: '',
	k			: '',
	CommentAllowed: true,
	FeedUrl		: 'http://livefeed.mynet.com/app/feed.php?cf=?&op=g',
	NotificationUrl : 'http://notification.mynet.com/GetNotifications.php?cf=?',
	GeneralFeedUrl: 'http://livefeed.mynet.com/app/feed.php?cf=?&op=gf',
	CommentUrl: 'http://livefeed.mynet.com/app/comment.php',
	LikeUrl:'http://livefeed.mynet.com/app/like.php',
	WaitingIcon: '<img src="http://img3.mynet.com/feed/loadComment.gif" />',
	ShowNotificationCount: function()  {
							if (Cookie.TotalNotifications > 0) {
								jFeed('#notification_count').html('('+Cookie.TotalNotifications+')');
							}else {
								jFeed('#notification_count').html('');
							}
						},
	GetGeneralFeeds : function () {
						jFeed('#' + Layout.moreFeedWidget).html('Yükleniyor...');
						jFeed.ajax({
							type: 'GET',
							url: this.GeneralFeedUrl,
							data: 'pageowner_id='+this.PageOwnerId+'&app_id='+this.AppId+'&k='+this.k+'&limit='+this.PagingGeneralFeed.limit,
							dataType: 'jsonp',
							success: function(data) {
								var defaultShowNumber = 5;
								var totalNum = data.f.length;
								if (totalNum <= defaultShowNumber) {
									var rotate = 0;
									FeedParser.Parse(data);
								}else {
									var rotate = totalNum - defaultShowNumber;
									//put default ones
									FeedParser.tmp = new Object();
									FeedParser.tmp.f = new Array();
									FeedParser.tmp.t = data.t;
									FeedParser.tmp.f = data.f.slice(rotate,totalNum);
									FeedParser.ShowMoreLink = false;
									FeedParser.Position = 'prepend';
									FeedParser.Parse(FeedParser.tmp);
									//Take rotating ones	
									FeedParser.RotateFeeds = data.f.slice(0,rotate);
									FeedParser.RotateFeeds.t = data.t;
									//Configure set time out
									var passedTime = 0;
									for (i=rotate-1;i>=0;i--) {
										//Generate random time for each item.
										var timeout = Math.floor(Math.random()*11);
										passedTime += timeout;
										FeedParser.Rotate(i, passedTime);
									}	
								}
							},
							error: this.HandleError
						});
					},
	GetFeeds 	: function () {
					jFeed('#' + Layout.moreFeedWidget).html('Yükleniyor...');
					
					jFeed.ajax ({
						type: 'GET',
						url: this.FeedUrl,
						data: 'pageowner_id='+this.PageOwnerId+'&app_id='+this.AppId+'&k='+this.k+'&page='+this.PagingFeed.page+'&limit='+this.PagingFeed.limit,
						dataType: 'jsonp',
						success: function (data) {
								FeedParser.Parse(data);
								Feeds.isFeedComplete = true;		
						},
						error: this.HandleError
					});
				},
	jsonReady	: true,
	GetAllNotifications : function() {
							jFeed.ajax({
								type: 'GET',
								url: this.NotificationUrl,
								dataType: 'jsonp',
								data: 'op=g&limit=' + Feeds.PagingNotification.limit + '&page=' + Feeds.PagingNotification.page,
								success: function (data) {
									NotificationParser.Parse(data);
									//indicates request is done and avaible for other requests
									Control.requestDone();
								},
								error: this.HandleError
							});
				},
	GetUnreadNotifications: function() {
							jFeed.ajax({
								type: 'GET',
								url: this.NotificationUrl,
								dataType: 'jsonp',
								data: 'op=u&limit=' + this.PagingNotification.limit,
								success: function (data) {
									NotificationParser.Parse(data);
									//indicates request is done and avaible for other requests
									Control.requestDone();
								},
								error: this.HandleError
							});	
						},
	GetNotificationContentDiv: function() {
								if (this.CurrentTab == 'unread') {
									return 'p_unread';
								}else if (this.CurrentTab == 'all') {
									return 'p_all';
								}else {
									return 'p_unread';
								}	
							},
	HandleError		: function(data) {
						alert('Bir hata oluştu lütfen sonra bir daha deneyiniz');
					}		
	};
	
	
	var FeedParser = {
		RotateFeeds	 : '',
		Position : 'append',
		ShowMoreLink : true,
		Rotate: function (i, timeout) {
				setTimeout(function(){
					var tmp = new Object();
					tmp.f = new Array();
					tmp.f[0] = FeedParser.RotateFeeds[i];
					tmp.t = FeedParser.RotateFeeds.t;
					FeedParser.Parse(tmp);
				},timeout * 1000);
			},
		Parse: function (data) {
				if (data.f.length > 0) {
					jFeed.each(data.f, function (i,lineData) {
						var uniqueId = "feed_"+lineData.fid;
						if (jFeed('#' + uniqueId).length == 0) {
							var xhtmlContent = '<div id="'+uniqueId+'">'
												+ lineData.c
												+ '</div>';
							if (FeedParser.Position == 'append') {
								jFeed('.newFeedContain').append(xhtmlContent);
							}else if(FeedParser.Position == 'prepend') {
								jFeed('.newFeedContain').prepend(xhtmlContent);
							}
							jFeed('#' + uniqueId + ' div.newFeedContent div.newFeedContentContain div.newFeedBar').append('<span class="newFeedUserInfo"> ('+DateParser.getDifference(lineData.dt, data.t) + ')</span>');
							if (Feeds.CommentAllowed) {
								FeedParser.CommentLayout(lineData.fid, uniqueId, lineData.app, lineData.source, lineData.h);						
								FeedParser.ShowActions(lineData.fid, lineData.fl);
								Flike.ShowLikers(lineData.fl,lineData.tl,lineData.app,lineData.fid);
								Fcomment.ShowFriendCommenters(lineData.fc,lineData.tc,lineData.app,lineData.fid);
								Fcomment.ShowComments(lineData.co, lineData.tc, lineData.fid, lineData.app, data.t, lineData.source);
								
							}
							
							var imgPath = Avatar.getPicture(lineData.source);
							var img = '<img src="'+imgPath+'" onerror="Avatar.getDefault(this)"/>';
							jFeed('#' + uniqueId + ' span[class=feedSourceImage]').html(img);
							if (lineData.app != Feeds.AppId) {
								jFeed('#'+ uniqueId+' a').attr('target', '_blank');
							}
							if (i==0) {
								return;
							}
						}
					});
				}else {
					jFeed('.newFeedContain').append('Yeni bir haber yok.');
				}
				FeedParser.BindActions();
								
				jFeed('.fVideoLink').unbind('click').bind('click', function(){
					var videoId = jFeed(this).attr('vid');
					jFeed(this).parents('div[class=newFeedVideo]').attr('id','newFeedVideo');
					fVideo.playVideo(videoId,'newFeedVideo');
				});
				
				jFeed('.fPhotoLink').unbind('click').bind('click', function(){
					jFeed(this).attr('rel','div.overlay');
					
					var image = new Image();
					image.onload = function() {
						FeedParser.SetImageDim(this);
					};
					var photoLink = jFeed(this).attr('src');
					var tmp = photoLink.lastIndexOf(".");
					var bigPhotoLink = photoLink.substr(0,tmp-1) + 'b' + photoLink.substr(tmp);
					image.src = bigPhotoLink;
					jFeed('#fPhotoOverlay').html('<a onclick="jFeed.closeOverlay();" class="closePhoto">Kapat</a>').append(image).append('<div class="fPhotoTitle">'+jFeed(this).attr('title')+'</div>');
				});
				if (FeedParser.ShowMoreLink) {
					FeedParser.configureMoreLink(data.f.length);
				}else {
					jFeed('#' + Layout.moreFeedWidget).html('');
				}
		},
		CommentLayout: function (feed_id, unique_id, app_id, uid, hash) {
					var xhtmlContent = '<div class="feedCommentsContain clr" fid="'+feed_id+'" aid="'+app_id+'" uid="'+uid+'" id="'+hash+'">';
					xhtmlContent += '<div class="feedCommentButton clr">';
					xhtmlContent += '</div>';
					xhtmlContent += '<div class="feedCommentLikeContain clr"></div>';
					xhtmlContent += '<div class="feedCommentFriendContain clr"></div>';
					xhtmlContent += '<div class="feedCommentContent clr"></div>';
					xhtmlContent += '<div class="feedAddContain" style="display:none;"><textarea name="body"></textarea><input type="button" value="Gönder" class="feedCommentAdd" /><a  class="feedCommentCancel">Vazgeç</a><span class="f_error"></span></div>';
					xhtmlContent += '</div>';
					jFeed('#' + unique_id + ' div.newFeedContentContain' ).append(xhtmlContent);
		},
		ShowActions: function(feed_id,fLikes){
					var patt = new RegExp('(^|,)' + fLikes.toString() + '(,|$)',"i");
					var xhtmlContent = "";
					xhtmlContent += '<a  class="c_feed">Yorumla</a> - '; 
					//Check user has already liked it.
					if (patt.test(Feeds.Username) && Feeds.Username != "") {
						xhtmlContent += '<a class="l_feed" s="1">Beğenmekten vazgeç</a>';
					}else {
						xhtmlContent += '<a class="l_feed" s="0">Beğen</a>';
					}
					jFeed(".feedCommentsContain[fid=" + feed_id + "] div.feedCommentButton").html(xhtmlContent);
					
		},
		BindActions: function(){
				jFeed('.feedCommentButton  a').each(function(){
					var action = jFeed(this).attr('class');
					
					//Check username for any action
					if (Feeds.Username == "") {
						jFeed(this).attr('rel','div.overlay').unbind('click').bind('click',function(){
							myHtmlLogin.login();
						});
					}else {
						//Bind Comment actions
						if (action == 'c_feed') {
							jFeed(this).unbind('click').bind('click',function(){
								jFeed(this).parents('.feedCommentsContain').children('div.feedAddContain').toggle().children('textarea').focus();
							});
						//Bind Like action
						}else if (action == 'l_feed') {
							jFeed(this).unbind('click').bind('click',function(){
								jFeed(this).append(Feeds.WaitingIcon);
								var feed_id = jFeed(this).parents('.feedCommentsContain').attr('fid'); 
								var hash = jFeed(this).parents('.feedCommentsContain').attr('id');
								var status = jFeed(this).attr('s');
								if (status == "0") {
									Flike.ChangeLike(feed_id,'set', hash);
								}else if (status == "1") {
									Flike.ChangeLike(feed_id,'unset', hash);
								}
							});
						}						
					}
				});
				
				//More comment action
				jFeed('.moreComment').unbind('click').bind('click', function(){
					var feed_id = jFeed(this).parents('.feedCommentsContain').attr('fid');
					var feedAddContain = jFeed(this).parents('.feedCommentsContain').children('div.feedAddContain'); 
					Fcomment.MoreComments(feed_id);
					feedAddContain.toggle().children('textarea').focus();
				});
				
				jFeed('textarea[name=body]').unbind('keyup').bind('keyup', function(event){
					if (event.keyCode == 13) {
						jFeed(this).nextAll('.feedCommentAdd').click();
					}
				});
				
				//Add comment action
				jFeed('.feedCommentAdd').unbind('click').bind('click',function(){
					if (Feeds.Username == "") {
						myHtmlLogin.login();
					}else {
						Fcomment.Save(jFeed(this));
					}
				});
				//Binding cancel comment action
				jFeed('.feedCommentCancel').unbind('click').bind('click', function(){
					jFeed(this).parent().hide();
				});
				
				
		},
		SetImageDim: function (element) {
					jFeed('#fPhotoOverlay').css({width: element.width, height: element.height});
					jFeed('#fPhotoOverlay').jOverlay();
		},
		configureMoreLink: function(totalNum) {
			var moreLink = jFeed('#' + Layout.moreFeedWidget);
			Feeds.PagingFeed.page+=1;
			if (totalNum > 0) {
				moreLink.html('<a>Daha fazla göster</a>').show();
			}else {
				moreLink.html('').hide();
			}
		}
	};
	
	var NotificationParser = {
		Parse		: function (data) {
						var xhtmlContent = "";
						var notificationContentDiv = Feeds.GetNotificationContentDiv();
						var readCount = 0;
						if (data.d.length > 0) {
							jFeed.each(data.d, function (i, lineData) {
								xhtmlContent += '<li class="bildirimListContain ';
								if (lineData.st == 0) {
									xhtmlContent += 'bListDeactive ';
								}else {
									readCount +=1;
								}
								xhtmlContent	+='clr">'
												 + lineData.c
												 + '<span class="listTime">('+DateParser.getDifference(lineData.dt, data.t)+')</span>'
												 + '</li>';
							});
							//Append for coming notifications
							if (Feeds.PagingNotification.isAppend) {
								jFeed('#' + notificationContentDiv).append(xhtmlContent);
							}else {	//If it is first page, change all html	
								jFeed('#' + notificationContentDiv).html(xhtmlContent);
							}
						}else {
							//jFeed('#' + Layout.moreNotificationWidget).html('Okunmamış bildirim bulunmamaktadır').show();
							//Display none for more link
						}
						NotificationParser.configureMoreLink(data.d.length,readCount);
						
		},
		configureMoreLink : function (totalNum, readCount) {
								Feeds.PagingNotification.isAppend = true;
								var moreLink = jFeed('#'+Layout.moreNotificationWidget);
								if (totalNum > 0) {
									moreLink.html('<a>Daha fazla göster</a>');
								}else {
									if (Feeds.CurrentTab == 'unread') {
										var text = 'Okunmamış bildirim bulunmamaktadır';
									}else {
										var text = 'Daha fazla bildirim bulunmamaktadır';
									}
									moreLink.html(text).unbind('click');
								}
								if (Feeds.CurrentTab == 'all') {
									Feeds.PagingNotification.page += 1;
									moreLink.unbind('click');
									moreLink.bind('click', function() {Feeds.GetAllNotifications();});
								}else {
									moreLink.unbind('click');
									moreLink.bind('click', function() {Feeds.GetUnreadNotifications();});
								}
								if (readCount > 0) {
									var newTotal = Cookie.TotalNotifications - totalNum;
									if (newTotal > 0) {
										Cookie.SetNotificationCountCookie(newTotal);
									}else {
										Cookie.SetNotificationCountCookie(0);
									}
								}
								
		}
	};
	
	var Cookie = {
		TotalNotifications : '',
		CookieName : 'mylcount',
		GetCookie : function() {
						var c=document.cookie;
						var name = Cookie.CookieName;
						if (c.indexOf(name)!=-1) { 
        					if(c.substr(c.indexOf(name)+name.length,1) !== "=") return false;
							pos1=c.indexOf("=", c.indexOf(name))+1; 
        					pos2=c.indexOf(";",pos1);  
       						if(pos2==-1)    pos2=c.length;
       						data=c.substring(pos1,pos2);
       						data = data.split('.');
       						return data;
						}else {
							return false;
						}
						
					},
		GetNotificationCountCookie : function() {
										var data = this.GetCookie();
										if (data == false || data[2] == -1) {
											this.GetNotificationCount();
										}else {
											Cookie.TotalNotifications = data[2];
										}
									},
		
		SetNotificationCountCookie : function(count) {
										Cookie.TotalNotifications = count;
										Feeds.ShowNotificationCount();
										var date = new Date();
 												date =  Math.floor(date.getTime());
 												var cookie = Cookie.GetCookie();
 												if (cookie == false) {
 													var data = '0'+'.'+date+'.'+Cookie.TotalNotifications+'.'+date+'.'+'0'+'.'+date+'.'+'0'+'.'+date;
 												}else {
 													var data= cookie[0]+'.'+cookie[1]+'.'+Cookie.TotalNotifications+'.'+date+'.'+cookie[4]+'.'+cookie[5]+'.'+cookie[6]+'.'+cookie[7];
 												}
 												Cookie.setCookie(Cookie.CookieName,data,5,"/", ".mynet.com");
									},
		
		GetNotificationCount: function () {
								jFeed.ajax({
										type: 'GET',
										url: Feeds.NotificationUrl,
										dataType: 'jsonp',
										data:'op=n',
										success:function (data) {Cookie.SetNotificationCountCookie(data.count);}, 
										error: this.HandleError
									});
							},
		

		setCookie: function(name, value, dakika, path, domain, secure){
					if(value.length > 4000)	return false;
					if(dakika !== 0 ){
						var d=new Date();
						d.setTime(d.getTime()+(dakika*60*1000));
						var expires="; expires="+d.toGMTString();  
					}else{
						var expires = "";
					}
					var path = path ? 	  ";path="+path:';path=/';
					var domain = domain ? ";domain="+domain:'';
					var secure = secure ? ";secure="+secure:'';
					document.cookie = name+"="+value+expires+path+domain+secure;
				}
		};
		
	var Layout = {
		moreFeedWidget: 'showMoreFeed',
		moreNotificationWidget: 'showMoreNotification',
		Container : '',
		showNotification : true,
		IsOpen: function(){
					if (jFeed('#notificationClose').hasClass('bUp')) {
						return true;
					}else {
						return false;
					}
				},
		IsClose: function(){
					if (jFeed('#notificationClose').hasClass('bDown')) {
						return true;
					}else {
						return false;
					}
				},
		Open: function(){
				jFeed('#notificationClose').removeClass('bDown').addClass('bUp').html('Gizle');
				jFeed('#notification_place').show();
			},
		Close:function(){
				Feeds.PagingNotification.isAppend = false;
				jFeed('#notificationClose').removeClass('bUp').addClass('bDown').html('Göster');
				jFeed('#notification_place').hide();
		},
		ArrowClick: function(){
				if (Layout.IsClose()) {
					
					if (Feeds.CurrentTab == 'unread') {
						Feeds.GetUnreadNotifications();
					}else if (Feeds.CurrentTab == 'all') {
						Feeds.PagingNotification.page = 1;
						Feeds.GetAllNotifications();
					}
					Layout.Open();
					
				}else if (Layout.IsOpen()) {
					Layout.Close();
					jFeed('#'+Feeds.GetNotificationContentDiv()).empty();
				}
		},
		UnreadTabClick: function() {
				//Check avaible for request
				if (!Control.isRequestAvailable()) {
					return false;
				}else {
					//indicate request is taken for unread notifications
					Control.requestSend();
				}
				Feeds.PagingNotification.isAppend = false;
				jFeed('#l_unread').addClass('bTabLinkActive');
				jFeed('#l_all').removeClass('bTabLinkActive');
				Feeds.CurrentTab = 'unread';
				/*if (jFeed('#p_unread').html().length == 0) {
					Feeds.GetUnreadNotifications();
				}*/
				Feeds.GetUnreadNotifications();
				if (Layout.IsClose()) {Layout.Open()};
				jFeed('#p_all').hide().empty();
				jFeed('#p_unread').show();
		},
		AllTabClick: function() {
				if (!Control.isRequestAvailable()) {
					return false;
				}else {
					//indicate request is taken for unread notifications
					Control.requestSend();
				}
				Feeds.PagingNotification.isAppend = false;
				Feeds.PagingNotification.page = 1;
				jFeed('#l_unread').removeClass('bTabLinkActive');
				jFeed('#l_all').addClass('bTabLinkActive');
				Feeds.CurrentTab = 'all';
				
				/*if (jFeed('#p_all').html().length == 0) {
					Feeds.GetAllNotifications();
				}*/
				Feeds.GetAllNotifications();
				if (Layout.IsClose()){Layout.Open();};
				jFeed('#p_unread').hide().empty();
				jFeed('#p_all').show();
		},
		GenerateLayout : function(){
			var xhtmlContent = "";
			//Notification Div
			if (this.showNotification) {
				xhtmlContent 	+= '<div class="bildirimContain clr">';
				xhtmlContent	+= '<div class="bildirimTitleContain clr">';
				xhtmlContent	+= '<h2 class="bildirimTitle">Bildirimler</h2>';
				xhtmlContent	+= '<a  class="bTabLink" id="l_unread">Okunmamışlar<span id="notification_count" style="display:inline;"></span></a><a  class="bTabLink" id="l_all">Tümü</a>';
				xhtmlContent 	+= '<a  id="notificationClose" class="bildirimUpDown bDown">Göster</a>';
				xhtmlContent	+= '</div>';
				xhtmlContent	+= '<div id="notification_place"  style="display:none;">';
				xhtmlContent	+= '<ul class="unread_notifications" id="p_unread"></ul>';
				xhtmlContent	+= '<ul class="all_notifications" id="p_all" style="display:none;"></ul>';
				xhtmlContent	+= '<div class="blinkAllContain" id="'+this.moreNotificationWidget+'"><a>Daha fazla göster</a></div>';
				xhtmlContent 	+= '</div>';
				xhtmlContent 	+= "</div>";
			}else {
				
			} 
			
			//Init Feed Div
			xhtmlContent += '<div class="feedHiddenButtonBac clr"><div class="feedBslContain">Haberlerim</div><a id="feedClose" class="bildirimUpDown bUp">Gizle</a></div>';
			xhtmlContent += '<div class="newFeedContain clr">';
			xhtmlContent += '</div>';
			
			//Photo Overlay
			xhtmlContent += '<div id="fPhotoOverlay" style="display:none;" rel="div.overlay"></div>';
			
			xhtmlContent += '<div id="'+this.moreFeedWidget+'"></div>';
			jFeed('#' + this.Container).html(xhtmlContent);
			jFeed('#'+this.moreFeedWidget).bind('click', function(){Feeds.GetFeeds();});
			jFeed('#feedClose').bind('click', function(){
				var status = jFeed(this).html();
				if (status == 'Gizle') {
					jFeed(this).removeClass('bUp').addClass('bDown');
					jFeed(this).html('Göster');
				}else {
					jFeed(this).removeClass('bDown').addClass('bUp');
					jFeed(this).html('Gizle');
				}
				jFeed('.newFeedContain').toggle();
				jFeed('#'+Layout.moreFeedWidget).toggle();
			});
			
			
			//Bind Necessary actions to Links
			jFeed("#notificationClose").bind('click',this.ArrowClick);
			jFeed("#l_unread").bind('click', this.UnreadTabClick);
			jFeed("#l_all").bind('click', this.AllTabClick);
		}
	};
	var DateParser = {
		periods : new Array("saniye", "dakika", "saat", "gün", "hafta", "ay", "yıl", "asır"),
		lengths : new Array("60","60","24","7","4.35","12","100"),					
		getDifference: function (timestamp, currentDateTimeStamp) {
			var difference = currentDateTimeStamp - (timestamp);
			if (difference == 0) {
				return "az önce";
			}
			if (difference > 0) {
				var ending = " önce";
			}else {
				difference = -1 * difference;
				var ending = " sonra";
			}
			for (j=0; difference>=this.lengths[j]; j++) {
				difference /= (this.lengths[j]);
			}
			difference = Math.round(difference);
			return difference + ' ' + this.periods[j] + ending;
		}
	};
	var fVideo = {
		flashvars: {
			'videolist':'',
			'autoplay': '1'
		},
		params: {
			'allowScriptAccess':'always',
			'wmode': 'transparent',
			'allowFullScreen': true
		},
		attributes: {
			'id':'flash',
			'name': 'flash'
		},
		width: '480',
		height: '360',
		playerUrl: 'http://video.mynet.com/flvplayers/fvplayer.swf',
		videoListUrl: 'http://video.mynet.com/batch/video_xml_embed.php?video_id=',
		playVideo: function (videoId, placeHolder) {
					fVideo.flashvars.videolist = fVideo.videoListUrl + videoId;
					swfobject.embedSWF(fVideo.playerUrl, placeHolder, fVideo.width, fVideo.height, '9.0.0', 'expressIntall.swf', fVideo.flashvars, fVideo.params, fVideo.attributes );
		}
	};
	
	var Avatar = {
		eHash : [29,1000],
		eksenimUrl: 'http://i.eksenim.mynet.com/',
		getPicture: function (user) {
						var hash=0;
						for(var i=0;i<user.length;i++){
							hash *=this.eHash[0];
							hash +=user.charCodeAt(i);
							hash %=this.eHash[1];
						}
						var cavatar = this.eksenimUrl + hash + '/' + user + '/cavatar.jpg';
						return cavatar;
		},
		getDefault: function (img) {
				img.src = "http://s.mynet.com/eksn1/DefaultImages/avatar-m.gif";
		}
	};
	
	var Control = {
		waitingRequest : false,
		isRequestAvailable : function () {
								if (Control.waitingRequest) {
									return false;
								}else {
									return true;
								}
		},
		requestDone : function () {
						Control.waitingRequest = false;
		},
		requestSend : function () {
						Control.waitingRequest = true;
		}
	};

	var Flike = {
		ChangeLike: function(feed_id, status, hash){
			jFeed.ajax({
				type: 'GET',
				url: Feeds.LikeUrl,
				dataType: 'jsonp',
				data: 'op='+status+'&fid='+feed_id+'&username='+Feeds.Username + '&h=' + hash,
				success: function (data) {
					var element = jFeed('.feedCommentsContain[fid=' + feed_id + '] div.feedCommentButton a.l_feed');
					var app_id = jFeed('.feedCommentsContain[fid=' + feed_id + ']').attr('aid');
					if (data.result) {
						if (status == "set") {
							Flike.AddLikers(Feeds.Username, feed_id, app_id);
							element.attr('s',1).html('Beğenmekten vazgeç');			
						}else if (status == "unset") {
							Flike.RemoveLikers(Feeds.Username,feed_id);
							element.attr('s',0).html('Beğen');
						}
					}else {
						if (status == "set") {
							element.attr('s',1).html('Bunu önceden beğenmişsiniz.Beğenmekten vazgeç');
						}
					}
				},
				error: this.HandleError
			});
		},
		ShowLikers: function(feedLikers, totalLikes, app_id, feed_id) {
			var prefixProfileUrl = AppLinks.getAppProfile(app_id);
			var xhtmlContent = "";
			
			if (feedLikers.length > 0) {
				for (i=0; i<feedLikers.length; i++) {
					var profileLink = prefixProfileUrl + feedLikers[i];
					xhtmlContent += '<a href="' + profileLink + '">' + feedLikers[i] + '</a>, ';					
				}
			}
			if (feedLikers.length > 0) {
				xhtmlContent = xhtmlContent.substr(0,(xhtmlContent.length-2)); 
			}
			if ((totalLikes - feedLikers.length) > 0) {
				xhtmlContent += '<span class="otherLikes">';
				if (feedLikers.length > 0) {
					xhtmlContent += '<span class="conj"> ve </span>';
				}
				xhtmlContent += '<a onclick="Flike.FetchOthers(\''+feed_id+'\',\''+app_id+'\')">' + (totalLikes - feedLikers.length) + ' kişi</a> ';
				xhtmlContent += '</span>';
			}  
			if (feedLikers.length > 0 || (totalLikes - feedLikers.length) > 0) {
				xhtmlContent += " bunu beğendi";
			}
			jFeed('.feedCommentsContain[fid='+feed_id+'] div.feedCommentLikeContain').html(xhtmlContent);
		},
		AddLikers: function (username, feed_id, app_id) {
			var likeContain = jFeed('.feedCommentsContain[fid='+feed_id+'] div.feedCommentLikeContain');
			var userProfileLink = Flike.GetUserProfileLink(username,app_id); 
			if (likeContain.html() == "") {
				likeContain.html( userProfileLink + ' bunu beğendi');
			}else {
				if (likeContain.find('a').size() == 1) {
					likeContain.prepend(Flike.GetUserProfileLink(username,app_id) + '<span class="conj"> ve </span> ');
				}else {
					likeContain.prepend(Flike.GetUserProfileLink(username,app_id) + ', ');
				}
			}
		},
		RemoveLikers: function (username,feed_id) {
			var likeContain = jFeed('.feedCommentsContain[fid='+feed_id+'] div.feedCommentLikeContain'); 
			var rmRegexp = new RegExp (",?( *)?<a[^>]*>"+username+"<\/a>","i");
			var likeString = likeContain.html();
			likeString = likeString.replace(rmRegexp,'');
			var cmRegexp = new RegExp ("^(,| )*","i");
			likeString = likeString.replace(cmRegexp,'');
			likeContain.html(likeString);
			var numOfLinks = likeContain.find('a').size();
			if (numOfLinks == 0) {
				likeContain.html('');
			}else if (numOfLinks == 1) {
				likeContain.find('span.conj').remove();
			}
		},
		GetUserProfileLink : function(username, app_id){
			var profileLink = AppLinks.getAppProfile(app_id) + username;
			return '<a href="' + profileLink + '">' + username + '</a>';
		},
		FetchOthers: function (feed_id,app_id){
			jFeed.ajax({
				type:'GET',
				url:Feeds.LikeUrl,
				dataType:'jsonp',
				data:'op=g&fid='+feed_id,
				success:function(data) {
					var prefixProfileUrl = AppLinks.getAppProfile(app_id);
					var xhtmlContent = "";
					for (i=0; i<data.length; i++) {
						var profileLink = prefixProfileUrl + data[i];
						xhtmlContent += '<a href="'+profileLink+'">' + data[i] + '</a>';
						if (i == data.length-2) {
							xhtmlContent += '<span class="conj"> ve </span>';
						}else if (i== data.length-1) {
							xhtmlContent += " bunu beğendi ";
						}else {
							xhtmlContent += ", ";
						}
					}
					jFeed(".feedCommentsContain[fid="+feed_id+"] div.feedCommentLikeContain").html(xhtmlContent);
				},
				error: this.HandleError
			});
		}
	}	
	var Fcomment = {
		MaxLength : 255,
		ShowComments: function(objComment, totalComments, feed_id, app_id,time, feed_owner) {
			if (totalComments > 0) {
				var xhtmlContent = "";
				//Add First
				if (objComment.f.c != "") {
					xhtmlContent += Fcomment.ParseComment(objComment.f, app_id, time, feed_owner);
				}
				//More Link
				if (totalComments > 2) {
					var moreComment = totalComments - 2;
					xhtmlContent += '<div class="feedMoreComment"><a class="moreComment">'+moreComment+' yorum daha ...</a></div>';
				}
				
				if (typeof(objComment.l.c) != "undefined" && totalComments > 1) {
					xhtmlContent += Fcomment.ParseComment(objComment.l, app_id, time, feed_owner);
				}
				jFeed(".feedCommentsContain[fid="+feed_id+"] div.feedCommentContent").html(xhtmlContent);
			}
		},
		ParseComment: function (objComment, app_id, time, feed_owner) {
			var xhtmlContent = '<div class="feedCommentList clr" cid="'+objComment.cid+'">';
			xhtmlContent += objComment.c;
			xhtmlContent += ' - ' + AppLinks.getAppProfileLink(app_id,objComment.u);
			xhtmlContent += ' <span class="feedAddTime">(' + DateParser.getDifference(objComment.dt, time) + ') </span>';
			if (objComment.u == Feeds.Username || Feeds.Username == feed_owner) {
				xhtmlContent += '<a class="feedCommentDelete" onclick="Fcomment.Delete(this);">Sil</a>';
			}
			xhtmlContent += '</div>';
			return xhtmlContent; 
		},
		Save: function(element){
			var parent = element.parents('.feedCommentsContain');
			var feed_id = parent.attr('fid');
			var app_id = parent.attr('aid');
			var hash = parent.attr('id');
			
			var text = element.prev().val();
			if (jFeed.trim(text) == "") {
				return;
			}
			if (text.length > Fcomment.MaxLength) {
				element.parent().children('span.f_error').html('En fazla ' + Fcomment.MaxLength + ' karakter girebilirsiniz');
				return;
			}
			text = encodeURIComponent(text);
			Fcomment.DisableComment(element);
			jFeed.ajax({
				type: 'GET',
				url: Feeds.CommentUrl,
				dataType:'jsonp',
				data:'op=s&fid='+feed_id + '&c=' + text + '&u=' + Feeds.Username + '&h=' + hash,
				success: function (data) {
					if (data.result == -1) {
						myHtmlLogin.login();
					}
					if (data.status == 1) {
						var xhtmlContent = Fcomment.ParseComment(data.co,app_id, data.t);
						element.parents('.feedCommentsContain').children('div.feedCommentContent').append(xhtmlContent);
					}					
					Fcomment.EnableComment(element);
				}
			});
		},
		Delete: function(element){
			var cid = jFeed(element).parent().attr('cid');
			var fid = jFeed(element).parents('.feedCommentsContain').attr('fid');
			jFeed.ajax({
				type:'GET',
				url: Feeds.CommentUrl,
				dataType:'jsonp',
				data:'op=d&cid='+ cid + '&fid=' + fid,
				success: function(data) {
					if (data.result) {
						jFeed(element).parent().remove();
					}
				}
			});
		},
		DisableComment: function (element) {
			element.attr('disabled', true).parent().children('textarea').attr('disabled', true);
			element.parent().children('span.f_error').html(Feeds.WaitingIcon);
		},
		EnableComment: function(element) {
			element.attr('disabled', false).parent().children('textarea').attr('disabled', false).val('');
			element.parent().children('span.f_error').html('');
		},
		MoreComments: function(feed_id) {
			var container = jFeed('.feedCommentsContain[fid='+feed_id+']');
			var app_id = container.attr('aid');
			var uid = container.attr('uid');
			var hash = container.attr('id');
			
			container.children('div.feedCommentContent').children('div.feedMoreComment').html(Feeds.WaitingIcon);
			jFeed.ajax({
				type:'GET',
				url: Feeds.CommentUrl,
				data:'op=g&fid='+feed_id+'&h='+hash,
				dataType:'jsonp',
				success: function(data) {
					var xhtmlContent = "";
					jFeed.each(data.c, function (i, comment) {
						if (typeof(comment) == "object") {
							xhtmlContent += Fcomment.ParseComment(comment, app_id, data.t,uid);
						}
					});
					container.children('div.feedCommentContent').html(xhtmlContent);		
				}
			});
		},
		ShowFriendCommenters: function (friendCommenters, totalComments, appId, feedId) {
			
			var prefixProfileUrl = AppLinks.getAppProfile(appId);
			var xhtmlContent = "";
			
			if (friendCommenters.length > 0) {
				for (i=0; i<friendCommenters.length; i++) {
					if (friendCommenters[i] != Feeds.Username) {
						var profileLink = prefixProfileUrl + friendCommenters[i];
						xhtmlContent += '<a href="' + profileLink + '">' + friendCommenters[i] + '</a>, ';
					}
				}
			}
			if (friendCommenters.length > 0) {
				xhtmlContent = xhtmlContent.substr(0,(xhtmlContent.length-2)); 
			}
			  
			if (friendCommenters.length > 0 && (totalComments) > 2 && xhtmlContent != "" && Feeds.Username != "") {
				xhtmlContent = "Arkadaşlarından " + xhtmlContent + " buna yorum yazdı";
				//xhtmlContent += " buna yorum yazdı";
				jFeed('.feedCommentsContain[fid='+feedId+'] div.feedCommentFriendContain').html(xhtmlContent);
			}
		}
	};
	var AppLinks = {
		getApps: function(){
			var apps = new Array();
			apps["4c2a17c7f77ca1b2d39e26df0a164b8e"] = {"profile" : "http://kavun.mynet.com/#|profile/", 
														"link": "http://kavun.mynet.com",
														"name": "kavun"};
			apps["bbb8b4f18df1b4939ffa7af657eb76a7"] = {"profile" : "http://eksenim.mynet.com/",
														"link": "http://eksenim.mynet.com/",
														"name": "eksenim"};
			apps["6f8f2cee8c797fe3cc89759ce23123f9"] = {"profile" : "http://video.mynet.com/",
														"link": "http://video.mynet.com/",
														"name": "video"};
			return apps;
		},
		getAppProfile: function(app_id){
			var apps = AppLinks.getApps();
			return apps[app_id].profile;
		},
		getAppProfileLink: function (app_id, username) {
			var link = AppLinks.getAppProfile(app_id) + username;
			var xhtmlContent = '<a href="'+link+'">'+username+'</a>';
			return xhtmlContent;
		}
	}
	
	
	function Paginator(limit) {
		this.limit = limit;
		this.totalItems = '';
		this.totalPages = '';
		this.page		= 1;
		this.isAppend	= false;
		this.hasNextPage = function () {
							if (this.page >= this.totalPages) {
								return false;
							}else {
								this.page = this.page + 1;
								return true;		
							}
						};
	
	}