﻿var topID=0;

var proxy;
var sPage;
var _locData;

$(function (){
  var page = location.toString().split('/');
  page = page[page.length-1];
  if(page.indexOf("#")>=0)
		page = page.split('#')[0];
  if(page.length == 0 || page.indexOf("?")==0)
		page = "Default.aspx";
	else if(page.indexOf("?")>=0)
		page = page.split('?')[0];
  proxy = new ServiceProxy(page);
  initFlags();
  SetupPrompt();
  SetUpInfoOverlay(".infooverlay");
});

function initForm(selector){    
  $(selector + ' label').each(function (){
    $(this).wrap('<div class="frmLabel"></div>');
  });

  $(selector + ' input').each(function (){
    $(this).wrap('<div class="frmField"></div>');
  });
}

function initFlags(){
  $(".country > span[rel]").each(function (){
    $(this).click(function (){
      if (readCookie("_Midhold") != $(this).attr("rel")){
        var newlang = $(this).attr("rel")
        createCookie("_Midhold", newlang);
        Translate(newlang);
        TranslateWallet(newlang);
        TranslateLinks(newlang);
      }
    });
  });
}

/*function Translate(language){
  var sPath = window.location.pathname;
  sPage = sPath.substring(sPath.lastIndexOf('/') + 1, sPath.lastIndexOf('.'));
  if (sPage === null || sPage === "" || sPage === "/" || sPage.indexOf('/')>=0)
    sPage = "default";
  if (language)
    $.getJSON("Localization/" + sPage + "_" + language + ".js", '', function (msg, y){ TranslatePage(msg); }); 
  else if (readCookie("_Midhold") != null)
    $.getJSON("Localization/" + sPage + "_" + readCookie("_Midhold") + ".js", '', function (msg, y){ TranslatePage(msg); });
  else
    $.getJSON("Localization/" + sPage + "_en-US.js", '', function (msg, y){ TranslatePage(msg); });
}*/

function Translate(language){
  var sPath = window.location.pathname;
  sPage = sPath.substring(sPath.lastIndexOf('/') + 1, sPath.lastIndexOf('.'));
  if (sPage === null || sPage === "" || sPage === "/" || sPage.indexOf('/')>=0)
    sPage = "default";
  if (language)
    $.getJSON("Localization/" + sPage + "_" + language + ".aspx", '', function (msg, y){ TranslatePage(msg); }); 
  else if (readCookie("_Midhold") != null)
    $.getJSON("Localization/" + sPage + "_" + readCookie("_Midhold") + ".aspx", '', function (msg, y){ TranslatePage(msg); });
  else
    $.getJSON("Localization/" + sPage + "_en-US.aspx", '', function (msg, y){ TranslatePage(msg); });
}

function TranslateWallet(lang){
	$("#walletIframe").each(function (i){
		try{
			thehref = $(this).attr("src");
			var queryString = {};
			thehref.replace(new RegExp("([^?=&]+)(=([^&]*))?", "g"),function($0, $1, $2, $3) { queryString[$1] = $3; });
			var old_lang = queryString["lang"];
			if(old_lang!=lang){
				thehref = thehref.replace(old_lang, lang);
				$(this).attr("src",thehref);
			}
		}catch(e){}
	}).show();
}

function TranslateLinks(lang){
	$(".ml_link").each(function (i){
		try{
			thehref = $(this).attr("href");
			var old_lang = null;
			if(thehref.indexOf("en-US",true)>=0)
				old_lang = "en-us";
			else
				old_lang = "nl-nl";

			if(!lang)
				lang = readCookie("_Midhold");
			if(!lang)
				lang = "en-US";

			if(old_lang!=lang){
				thehref = thehref.toLowerCase().replace(old_lang, lang);
				$(this).attr("href",thehref);
			}
		}catch(e){}
	}).show();
}

function TranslatePage(msg){
  _locData = msg;
  TranslateIds();
  TranslateIdsL2();
  TranslateClasses();
  TranslateFavorites();
  TranslatePhotos();
  TranslateHead();
  TranslatePageing();
  TranslateSide();
  TranslateLinks();
}

function TranslateIds(){
	if (_locData.Label !== null){
		$(".t").each(function (i){
			if (this.id !== null && this.id !== ""){
				var totext = _locData.Label[this.id];
				$(this).html(totext);
			}
		}).show();
	}
}

function TranslateIdsL2(){
	if (_locData.Label !== null){
		$(".t2").each(function (i){
			if (this.id !== null && this.id !== ""){
				$(this).html(_locData.Label[this.id]);
				$(this).attr("title",_locData.Label[this.id+"_title"]);
			}
		}).show();
	}
}

function TranslateClasses(){
	if (_locData.Label !== null){
		$(".chat").each(function (i){
			$(this).html(_locData.Label["chat"]);
		});
		$(".nextimg").each(function (i){
			$(this).attr("title",_locData.Label["nextimg"]);
		});
		$(".previousimg").each(function (i){
			$(this).attr("title",_locData.Label["previousimg"]);
		});
		$(".itemrating").each(function (i){
			var rating = $(this).attr("rating");
			$(this).attr("title",String.format(_locData.Label["itemrating"], rating));
		});
		$(".profilelink").each(function (i){
			var name = $(this).attr("name");
			$(this).attr("title",String.format(_locData.Label["profilelink"], name));
		});
		//profile title
		$(".profileheadtext").each(function (i){
			var name = $(this).attr("nick");
			document.title = String.format(_locData.Label["pagetitle"], name).toTitleCase();
		});
	}
}

function TranslateFavorites(){
	$('#tabFavorites').html(String.format(_locData.Label["tabFavorites"], getNumFavorites()));;
	$(".addfav").each(function(index){
    var nick = $(this).attr("nick");
		$(this).attr("title",String.format(_locData.Label["favorites_add"], nick).toTitleCase());
		$(this).html("("+String.format(_locData.Label["favorites_add"], nick).toTitleCase()+")");
  });
	$(".delfav").each(function(index){
    var nick = $(this).attr("nick");
		$(this).attr("title",String.format(_locData.Label["favorites_delete"], nick).toTitleCase());
		$(this).html("("+String.format(_locData.Label["favorites_delete"], nick).toTitleCase()+")");
  });
  $(".camitem.favorite").each(function(index){
		var imgoverlay = $(this).find(".imgoverlay");
		if(imgoverlay){
			if($(this).hasClass("topcam"))
				imgoverlay.html("TopCammer / "+_locData.Label["favorite"]);
			else
				imgoverlay.html(_locData.Label["favorite"]);
			imgoverlay.fadeIn(2000);
		}
  });
  $(".camitem.topcam").each(function(index){
		var imgoverlay = $(this).find(".imgoverlay");
		if(imgoverlay){
			if(!$(this).hasClass("favorite"))
				imgoverlay.html("TopCammer");
			imgoverlay.fadeIn(2000);
		}
  });
}

function TranslatePhotos(){
	$("span.photos").each(function(){
    var index = $(this).attr("index");
    var totaal = $(this).attr("photos");
    var online = $(this).attr("online")==1?true:false;
    if(online)
			$(this).html(String.format("<span class=\"online\">online</span>"+_locData.Label["photoseries"], index, totaal));
    else
			$(this).html(String.format("<span class=\"offline\">offline</span>"+_locData.Label["photoseries"], index, totaal));
  });
}

function TranslateHead(){
	$(".profileheadtext").each(function(index){
    var nick = $(this).attr("nick");
		$(this).html(String.format(_locData.Label["profileheadtext"], nick).toTitleCase());
  });
  $("#pay_state").each(function(index){
    var paystate = $(this).attr("state");
    if(paystate == "paying")
			$(this).html(_locData.Label["isPaying"]);
  });
}

function TranslatePageing(){
	$("#camcount").each(function(index){
    var count = $(this).attr("count");
    var page = $(this).attr("page");
    if(page==0)
			$(this).html(String.format(_locData.Label["camcount"], count));
		else
			$(this).html(String.format(_locData.Label["campagescount"], count, page));
  });
}

function TranslateSide(){
	$(".freeshowhead").each(function(index){
    var nick = $(this).attr("nick");
		$(this).html(String.format(_locData.Label["freeshowhead"], nick.toTitleCase()));
  });
  $(".showstatus").each(function(index){
    var nick = $(this).attr("nick");
    var online = $(this).attr("online")==1?"online":"offline";
		$(this).html(String.format(_locData.Label["showstatus"], nick.toTitleCase(), online));
  });
  $(".nextshow").each(function(index){
		$(this).html(_locData.Label["nextshow"]);
  });
  $(".nextshow").each(function(index){
		$(this).html(_locData.Label["nextshow"]);
  });
  $(".showstarted").each(function(index){
		$(this).html(_locData.Label["showstarted"]);
  });
  $(".showstarting").each(function(index){
		$(this).html(_locData.Label["showstarting"]);
  });
  $(".showtoday").each(function(index){
    var time = $(this).attr("time");
		$(this).html(String.format(_locData.Label["showtoday"], time));
  });
  $(".shownottoday").each(function(index){
    var date = $(this).attr("date");
    var time = $(this).attr("time");
		$(this).html(String.format(_locData.Label["shownottoday"], date, time));
  });
  $(".gender").each(function(index){
    var gender = $(this).attr("gender");
		$(this).html(_locData.Label[gender]);
  });
}

/*Default Overlays*/

function SetupPrompt(){
	$("#prompt").overlay({
		expose: {
			color: '#FFF',
			loadSpeed: "slow",
			closeSpeed: 800,
			opacity: 0.8
		},
		oneInstance: true,
		closeOnClick: true,
		top: 'center', 
		left: 'center', 
		absolute: false
	});
}

function close_overlay(){
  $("#overlay .close").click();
}

function ShowError(){
	var questionhead = $(".questionheadWrap");
	var question = $(".questionWrap");
  
  if(questionhead && question)
		questionhead.toggleClass("error", true);
  
	questionhead.html(_locData.Label["error"]);
	question.html(_locData.Label["error_retry"]);
	
	var api = $("#prompt").overlay();
	api.load();
	delayed = new Object();
	imgreq = false;
}

function SetUpInfoOverlay(selector){
  $(selector).overlay({
		expose: {
			color: '#FFF',
			loadSpeed: "slow",
			closeSpeed: 800,
			opacity: 0.8
		},
    onBeforeLoad: function (){
			$(".overlay").css("width",600);
      var wrap = this.getContent().find(".contentWrap");
      thehref = this.getTrigger().attr("href");
      var lang = (readCookie("_Midhold") == null) ? "nl-NL" : readCookie("_Midhold");
			if(thehref.indexOf("?")>=0)
				thehref += "&lang="+lang;
			else
				thehref += "?lang="+lang;
      var infohtml = "<iframe id='infoframe' scrolling='auto' frameborder='0' style='border: solid 1px #000; width:600px; height: 400px;' src='"+thehref+"' />";
      wrap.html(infohtml);
    },
    closeOnClick: true,
    top: 'center', 
		left: 'center', 
		absolute: false
  });
}

/*Cookies*/

function createCookie(name, value, days){
  if(days==null||days==undefined)
		days = 365 * 50;
  var date = new Date();
  date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  var expires = "; expires=" + date.toGMTString();
  document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(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;
}

/*level 2 cookies*/

function eraseCookie(name){
	createCookie(name,null,-1);
}

function addCookie(name,value){
  var c=readCookie(name);
  if(c==null){
		createCookie(name,(value+","));
		return true;
	}
  else if(c.indexOf(",")>=0){
    var p = c.split(',');
    for(var i=0;i<p.length;i++){
      if(p[i]!=null && p[i] == value)
				return false;
    }
    c+=value+",";
    createCookie(name,c);
    return true;
  }
  else{
		c = value + ",";
    createCookie(name,c);
		return true;
	}
	return false;
}

function delCookie(name,value){
	var c = readCookie(name);
  if(c!=null){
    var p = c.split(',');
    var r = "";
    for(var i=0;i<p.length;i++){
      if(p[i]!=null && p[i] != '' && p[i]!=value)
				r+=p[i]+",";
    }
    if(r==c)
			return false;
    if(r.length>0)
			createCookie(name,r);
    else
			eraseCookie(name);
		return true;
  }
  return false;
}

function existsCookie(name,value){
	var c = readCookie(name);
  if(c==null)
		return false;
	else if(value==null || value == undefined)
		return true;
	else{
    var p = c.split(',');
    var r = "";
    for(var i=0;i<p.length;i++){
      if(p[i]!=null && p[i] == value)
				return true;
    }
  }
  return false;
}

var cookieEnabled = false;

function supportsCookie(){
	if(!cookieEnabled){
		createCookie("test", "test", 1);
		if(readCookie("test")=="test")
			cookieEnabled = true;
	}
	return cookieEnabled;
}

/*favorites*/

function addFavorite(id){
	return addCookie("favorites", id);
}

function delFavorite(id){
	return delCookie("favorites", id);
}

function existsFavorite(id){
	return existsCookie("favorites", id);
}

function hasFavorites(){
  return existsCookie("favorites");
}

function getNumFavorites(){
  var c = readCookie("favorites");
  if(c == null)
		return 0;
	else{
    var count = 0;
    var p = c.split(',');
    for(var i=0;i<p.length;i++){
      if(p[i]!=null && p[i] != "")
				count++;
    }
    return count;
  }
}

/*Strings*/

String.format = function( text ){
  if ( arguments.length <= 1 || text == undefined)
    return text;
  var tokenCount = arguments.length - 2;

  for( var token = 0; token <= tokenCount; token++ )
  {
    text = text.replace( new RegExp( "\\{" + token + "\\}", "gi" ), arguments[ token + 1 ] );
  }
  return text;
};

String.prototype.toTitleCase = function(){
  if ( this.length <= 0 || this == undefined)
    return this;
  return this.substring(0,1).toUpperCase()+this.substring(1,this.length);
};

function RemoveHtmlMarkup(s){ 
	s = s.replace(/&amp;/g," ");
	s = s.replace(/amp;/g,"");
	s = s.replace(/quot;/g,"\"");
	s = s.replace(/#160;/g,"");
	s = s.replace(/#235;/g,"");
	return s;
} 

/*Bookmark*/
function bookmark(url, title){
	var u=url?url:document.location;
	var t=title?title:document.title;
  if(document.all){window.external.AddFavorite(u,t);}
  else if(window.sidebar){window.sidebar.addPanel(t, u,"");}
  else if(window.opera && window.print){return true;}
}