﻿$(function () {
	try{
		window.moveTo(0,0);
		window.resizeTo(screen.availWidth, screen.availHeight);
  }catch(e){}
  getCammer();
})

function getCammer(){
	try{
		var camid = document.location.toString().substring(document.location.toString().indexOf("#")+2,document.location.toString().length);
		if(camid>0){
			proxy.getCam(camid, function (msg) { CamsReceived(msg); });
		}
	}catch(e){
		if(document.location.toString().indexOf("#")>=0)
			document.location = document.location.toString().substring(0,document.location.toString().indexOf("#")).replace("profile/","");
		else
			document.location = document.location.toString().replace("profile/","");
	}
	try{
		var camid = 0;
		if(document.location.toString().indexOf("#!cammer=")>=0)
			camid = document.location.toString().substring(document.location.toString().indexOf("#!cammer=")+9,document.location.toString().length);
		else if(document.location.toString().indexOf("#!")>=0)
			camid = document.location.toString().substring(document.location.toString().indexOf("#!")+2,document.location.toString().length);
		else
			throw("no hash found");
		if(camid>0){
			proxy.getCam(camid, function (msg) { CamsReceived(msg); });
		}
	}catch(e){
		if(document.location.toString().indexOf("#")>=0)
			document.location = document.location.toString().substring(0,document.location.toString().indexOf("#")).replace("profile/","");
		else
			document.location = document.location.toString().replace("profile/","");
	}
}

function CamsReceived(msg){
  cammerData = msg;
  $("#pane").setTemplateURL('../htmltemplates/profile.htm?15');
  $("#pane").processTemplate(msg);
  OnCamsCompleteInfo();
}

function OnCamsCompleteInfo(selector){
	if(supportsCookie())
		SetupFavorites("#pane span.modalInput");
	else
		SetupCookieWarning("#pane span.modalInput");
	SetUpImgPaging("#pane");
  Translate();
  ScheduleCamStateUpdate();
  proxy.getPayState(function (msg){PayStateReceived(msg);});
}

function PayStateReceived(msg, camid) {
	if(cammerData && cammerData.Cammers && cammerData.Cammers[0] && cammerData.Cammers[0].Chat){
		if(msg.result=="paying")
			$("#directLink").fadeIn("slow");
		else
			$("#walletIframe").fadeIn("slow");
	}

}

var delayed = new Object();

function ScheduleCamStateUpdate(){
	if(delayed.timeoutID)
		window.clearTimeout(delayed.timeoutID);
	delayed.timeoutID = setTimeout(CamStateUpdate,30000);
}

function CamStateUpdate(){
	$("#statusholder span").html("refreshing...");
	$("#statusholder span").toggleClass("online offline", false);
	$("#statusholder span").addClass("refresh");
	delayed.timeoutID = setTimeout(UpdateCamState,1000);
}

function UpdateCamState(){
	var camid = $("#statusholder").attr('camid');
	//proxy.getCamState(camid, function (msg) { CamStateReceived(msg); });
	proxy.getCamAndPayState(camid, function (msg) { CamAndPayStateReceived(msg); });
	delayed.timeoutID = setTimeout(CamStateUpdate,30000);
}

function CamStateReceived(msg) {
  msg.online=(msg.online==1?true:false);
  $("#statusholder span").html((msg.online?"online":"offline"));
  $("#statusholder span").toggleClass("refresh online offline", false);
	$("#statusholder span").addClass((msg.online?"online":"offline"));
}

var lastMsg = null;

function CamAndPayStateReceived(msg) {
  msg.online=(msg.online==1?true:false);
  msg.paying=(msg.paying==1?true:false);
  $("#statusholder span").html((msg.online?"online":"offline"));
  $("#statusholder span").toggleClass("refresh online offline", false);
	$("#statusholder span").addClass((msg.online?"online":"offline"));
	if(lastMsg){
		if(lastMsg.paying != msg.paying){
			if(msg.paying){
				$("#walletIframe").fadeOut("slow");
				if(msg.online)
					$("#directLink").fadeIn("slow");
			}
			else {
				$("#directLink").fadeOut("slow");
				if(msg.online)
					$("#walletIframe").fadeIn("slow");
			}
		}
		else if(lastMsg.online != msg.online){
			if(msg.online){
				if(msg.paying)
					$("#directLink").fadeIn("slow");
				else
					$("#walletIframe").fadeIn("slow");
			}
			else{
				if(msg.paying)
					$("#directLink").fadeOut("slow");
				else
					$("#walletIframe").fadeOut("slow");
			}
		}
	}
	lastMsg = msg;
}

function SetupFavorites(selector) {
	$(selector).click(function(e) {
			var currTrigger = $(this);
			//currTrigger.blur();
      var camid = currTrigger.attr("camid");
      var nick = currTrigger.attr("nick");
      if(existsFavorite(camid)&&delFavorite(camid)){
				currTrigger.removeClass("delfav");
				currTrigger.addClass("addfav");
				
				var nick = currTrigger.attr("nick");
				currTrigger.attr("title",String.format(_locData.Label["favorites_add"], nick).toTitleCase());
				currTrigger.html("("+String.format(_locData.Label["favorites_add"], nick).toTitleCase()+")");
				
				var item = currTrigger.parents(".camitem");
				item.removeClass("favorite");
				
				var imgoverlay = item.find(".imgoverlay");
				if(imgoverlay){
					if(item.hasClass("topcam"))
						imgoverlay.html("TopCammer");
					else
						imgoverlay.fadeOut(2000);
				}
      }
			else if(addFavorite(camid)){
				currTrigger.removeClass("addfav");
				currTrigger.addClass("delfav");
				
				var nick = currTrigger.attr("nick");
				currTrigger.attr("title",String.format(_locData.Label["favorites_delete"], nick).toTitleCase());
				currTrigger.html("("+String.format(_locData.Label["favorites_delete"], nick).toTitleCase()+")");
				
				var item = currTrigger.parents(".camitem");
				item.addClass("favorite");
				
				var imgoverlay = item.find(".imgoverlay");
				if(imgoverlay){
					if(item.hasClass("topcam"))
						imgoverlay.html("TopCammer / "+_locData.Label["favorite"]);
					else{
						imgoverlay.html(_locData.Label["favorite"]);
						imgoverlay.fadeIn(1000);
					}
				}
			}
 	});
}

function SetupCookieWarning(selector) {
	$(selector).overlay({
		expose: {
			color: '#333',
			loadSpeed: 200,
			opacity: 0.9
		},
		oneInstance: true,
		onBeforeLoad: function () {
      var questionhead = this.getContent().find(".questionheadWrap");
			var question = this.getContent().find(".questionWrap");
      
			questionhead.html(_locData.Label["enable_cookies"]);
			question.html(_locData.Label["enable_cookies_explained"]);
    },
		closeOnClick: false
	});
}

var imgreq = false;
function SetUpImgPaging(selector) {
  $(selector+" .previousimg").click(function () {
		if(!imgreq){
			imgreq = true;
			if(delayed.timeoutID)
				window.clearTimeout(delayed.timeoutID);
			var obj = new Object();
			obj.camid = $(this).attr('camid');
			obj.nextImgIndex = getImgIndex(obj.camid, "down");
			$("#piclink_"+obj.camid+" .refresh").fadeIn("slow");
			delayed = obj;
			delayed.timeoutID = setTimeout('delayedGetCamImg()',1000);
		}
  });
  $(selector+" .nextimg").click(function () {
		if(!imgreq){
			imgreq = true;
			if(delayed.timeoutID)
				window.clearTimeout(delayed.timeoutID);
			var obj = new Object();
			obj.camid = $(this).attr('camid');
			obj.nextImgIndex = getImgIndex(obj.camid, "up");
			$("#piclink_"+obj.camid+" .refresh").fadeIn("slow");
			delayed = obj;
			delayed.timeoutID = setTimeout('delayedGetCamImg()',1000);
		}
  });
}

function delayedGetCamImg()
{
	if(imgreq)
		proxy.getCamImg(delayed.camid, delayed.nextImgIndex, function (msg) { ImgReceived(msg, delayed.camid); });
}

var pIndex = new Array();
function getImgIndex(camid, dir){
	if(pIndex.length>0){
		for(var i=0;i<pIndex.length;i++){
			if(camid==pIndex[i].camid){
				if(dir=="up")
					pIndex[i].index++;
				else
					pIndex[i].index--;
				return pIndex[i].index;
			}
		}
	}
	pic = new Object();
	pic.camid = camid;
	if(dir=="up")
		pic.index = 1;
	else
		pic.index = -1;
	pIndex[pIndex.length] = pic;
	return pic.index;
}

function ImgReceived(msg, camid) {
	msg.online=(msg.online==1?true:false);
	var photos = $("#piclink_"+camid+" .photos");
	var wasonline = true;
	if(photos.length>0)
		wasonline = photos.attr("online")==1?true:false;
	var picholder = $("#piclink_"+camid+" .picholder");
	if(msg.index==0)
		picholder.html("<img src=\""+msg.result+"\" alt=\"\" /><span class=\"livescreen\" ><span class=\""+(msg.online?"online":"offline")+"\" >"+(msg.online?"online":"offline")+"</span>live screenshot</span>");
	else
		picholder.html("<img src=\""+msg.result+"\" alt=\"\" /><span class=\"photos\" index=\""+msg.index+"\" photos=\""+msg.images+"\" online=\""+(msg.online?"1":"0")+"\"><span class=\""+(msg.online?"online":"offline")+"\" >"+(msg.online?"online":"offline")+"</span>"+String.format(_locData.Label["photoseries"], msg.index, msg.images)+"</span>");
	$("#piclink_"+camid+" .refresh").fadeOut("slow");
	if(wasonline!=msg.online){
		var item = picholder.parents(".camitem");
		var freechatlink = item.find("li.freechat");
		if(freechatlink){
			if(msg.online)
				freechatlink.fadeIn("slow");
			else
				freechatlink.fadeOut("slow");
		}
	}
	imgreq = false;
	CamStateReceived(msg);
	ScheduleCamStateUpdate();
}

// create custom animation algorithm for jQuery called "drop"  
$.easing.drop = function (x, t, b, c, d) {
	return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;
};

// create custom overlay effect for jQuery Overlay 
$.tools.overlay.addEffect("drop",
  function (done) {// loading animation
    var animateProps = {
      top: '+=55',
      opacity: 1,
      width: '+=20'
    };
    this.getOverlay().stop().animate(animateProps, "medium", 'drop', done).show();
  },
  function (done) {// closing animation 
    var animateProps = {
      top: '-=55',
      opacity: 0,
      width: '-=20'
    };
    this.getOverlay().stop().animate(animateProps, "fast", 'drop', function () {
      $(this).hide();
      done.call();
    });
  }
);

function spin(selector) {
  $(selector + ' .spinny').css({
    'display': 'block',
    'opacity': 0
  }).stop().animate({
    'opacity': 1
  },
  300);
}

function unspin(selector) {
  $(selector + ' .spinny').stop().animate({
    'opacity': 0
  },
  300);
}
