/*content loaded handler*/
function contentLoaded() {
    if (!window.onContentLoadedFunctions || window.onContentLoadedFunctions.length<1) return;
    for (var i=0; i<window.onContentLoadedFunctions.length; i++) {
        window.onContentLoadedFunctions[i]();
    }
    window.onContentLoadedFunctions = null;
}

function registerInit(callback) {
    if (document.addEventListener) {
        document.addEventListener('DOMContentLoaded', callback, false);
    }

    else if (/WebKit|Khtml/i.test(navigator.userAgent)) {
        if (!window.onContentLoadedFunctions) window.onContentLoadedFunctions = new Array();
        window.onContentLoadedFunctions.push(callback);
        var timer = setInterval(function() {
            if (/loaded|complete/.test(document.readyState)) {
                clearInterval(timer);
                contentLoaded();
            }
        }, 1);
    }

    else if (document.getElementById) {
        if (!this.initScript) {
            document.write('<script src="\/\/:" id="ie_onload" defer="defer"><\/script>');
            this.initScript = true;
        }
        var script = document.getElementById('ie_onload');
        if (script) {
            if (!window.onContentLoadedFunctions) window.onContentLoadedFunctions = new Array();
            window.onContentLoadedFunctions.push(callback);
            script.onreadystatechange = function() {
                if (this.readyState == 'complete') {
                    contentLoaded();
                }
            }
        }
    }

    else {
        if (!window.onContentLoadedFunctions) window.onContentLoadedFunctions = new Array();
        window.onContentLoadedFunctions.push(callback);
        window.onload = contentLoaded;
    }
}

function setDomain() {
	var pathname = location.pathname;
	var myDomain = pathname.substring(0,pathname.lastIndexOf('/')) +'/';
	return myDomain;
}
function setExpDate(days) {
	var largeExpDate = new Date ();
	largeExpDate.setTime(largeExpDate.getTime() + (days * 24 * 3600 * 1000));
	return largeExpDate;
}
function SetCookie (name, value) {
	var argv = SetCookie.arguments;
	var argc = SetCookie.arguments.length;
	var expires = (argc > 2) ? setExpDate(argv[2]) : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	var new_cookie = name + "=" + escape (value) +
	((expires == null) ? "" : ("; expires=" +
	expires.toGMTString())) +
	((path == null) ? "" : ("; path=" + path)) +
	((domain == null) ? "" : ("; domain=" + domain)) +
	((secure == true) ? "; secure" : "");
	document.cookie = new_cookie;
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}


/*var flashContainerId = '';*/


function playMovie(flvObj,idBox)
{
	/*var playos = (onstart)?onstart:false;*/
	/*var containerId = '';
	if (flashContainerId != '') containerId = flashContainerId;
	else {
		var paleyerConteiners = $$('.'+idBox);
		if (paleyerConteiners.length < 1) return;
		container = paleyerConteiners[paleyerConteiners.length-1];
		container.id = flashContainerId = containerId = 'currentPlayer';
	}*/
		var paleyerConteiner = $$('#tab_content_id .'+idBox)[0];
		if (!paleyerConteiner) return;
		paleyerConteiner.id = 'currentPlayer';
			so_s = new SWFObject("http://cdn-small.content.adultcentro.com/web/tmpl/1/intro/scenes_player.swf", "flash_sender", "100%", "100%", "9");
			so_s.addParam("quality", "high");
			so_s.addParam("scale", "noscale");
			so_s.addParam("swLiveConnect", "true");
			so_s.addParam("allowFullScreen", "true");
			so_s.addParam("allowScriptAccess", "always")
			so_s.addParam("wmode", "opaque");
			/*
			so_s.addVariable("en_flash_lib_path", designPath+"/flash/flash_player_lib.swf");
			

			if (!!window.scene_times_array) so_s.addVariable("en_flash_times_array", window.scene_times_array);
			
			so_s.addVariable("en_flash_buffer_video_on_init", "false");
			so_s.addVariable("en_flash_play_at_start", "true");
			so_s.addVariable("en_flash_debug_mode", 0);
			so_s.addVariable("en_flash_providerName", escape(flvObj.provider));
			so_s.addVariable("en_flash_flvFolder", escape(flvObj.dir));
			so_s.addVariable("en_flash_flvName", escape(flvObj.base));
			so_s.addVariable("en_flash_transitParams", escape(flvObj.params));
*/
			so_s.addParam("flashvars", "en_flash_xml=" + flvObj.flash_xml);
			so_s.write(paleyerConteiner.id);
			
			
			 so_s = new SWFObject(window.designPathPlayer + "/intro/scenes_player.swf", "flash_sender", "100%", "100%", "9");
				so_s.addParam("quality", "high");
		

}
function setCurrentQuality(link) {
	SetCookie('defaultQuality',link.up('li').className.split('_')[1],30);
	if (window.activeLink && $$('#tab_content_id .'+window.activeLink+' a')[0]) $$('#tab_content_id .'+window.activeLink+' a')[0].removeClassName('active');
	link.addClassName('active');
	window.activeLink = link.up('li').className;
	eval('var flvParams = ' + link.rel + ';');
	playMovie(flvParams,'flash_player');
	playMovie(flvParams,'hd_player');
}

function getContent(link) {
	var updatedBlock = link.rel;
	if ($(updatedBlock+'_opacity')) $(updatedBlock+'_opacity').className = 'opacity_block';
	if ($(updatedBlock+'_preloader')) $(updatedBlock+'_preloader').style.visibility = 'visible';
	new Ajax.Request(link.href+'&ajax=1&pager='+updatedBlock, {
	  method: 'get',
	  onSuccess: function(transport) {
		  $(updatedBlock+'_view').update(transport.responseText);
		  console.log(transport.responseText);
	  }
	});
	return false;
}

/**
 * Select boxes replacer
 * by ZeT, http://zet.od.ua
 * version 0.5.2007-02-02
 *
 * based on http://www.easy-designs.net/articles/replaceSelect2/
 */
var withoutId = 0;

var Sbr = {
	init: function(id) {
		this.last = false;
		this.trigger = false;
		
		var obj=null;
		if (id) {
			var obj = (id && typeof id == 'string' && document.getElementById(id)) ? document.getElementById(id) : id;
		}
		if (obj) {
			this.s = obj.getElementsByTagName('select');
		} else {
			this.s = document.getElementsByTagName('select');
			withoutId = 1;
		}
    	this.sCount = this.s.length;
		for (var i=0; i<this.sCount; i++) {
		  if (!this.s[i].multiple) {
  			if (!this.s[i].id) {
  				this.s[i].id = 'select_'+i;
  			}
		  	if (withoutId == 1 && this.s[i].id == 'chosenProblem') {
				/* select with ID 'chosenProblem' will be styled after popup window being loaded.
				 Identival styling class like "Sbr" was realized in popup.js*/
			} else {
				this.run(this.s[i], i);
			}
 		  }
		}
	},

	run: function(obj, counter) {
		/* building faux select structure*/
		var fauxSel = document.createElement('dl');
		fauxSel.className = obj.className ? obj.className + ' sbrWrap' : 'sbrWrap';
		obj.className = 'selReplaced';


for(i=0; i<= $$('.arrow_container').length -1; i++) {
		window.arrowClick = $$('.arrow_container')[i];
		window.arrowClick.onclick = function(){	
			var selectElement = this.next().nextSibling;
			if (this.next().childNodes[1].className == 'sbrOptsCol') {
				selectElement.onfocus();
				Sbr.last.className = 'sbrOptsCol';
				Sbr.last = this.next().childNodes[1];
				Sbr.trigger = false;
				document.onclick = function() { if (Sbr.trigger) Sbr.last.className = 'sbrOptsCol'; Sbr.trigger = true; }
				this.next().childNodes[1].className = 'sbrOptsExp';
			} else {
				Sbr.lastObjId = false;
				document.onclick = function() {	}
				this.next().childNodes[1].className = 'sbrOptsCol';
			}
			if (this.next().childNodes[0].className == '') {
				this.next().nextSibling.focus();
			}
		}
		
	}


		fauxSel.onclick = function() {	
			var selectElement = this.nextSibling;
			if (this.childNodes[1].className == 'sbrOptsCol') {
				selectElement.onfocus();
				Sbr.last.className = 'sbrOptsCol';
				Sbr.last = this.childNodes[1];
				Sbr.trigger = false;
				document.onclick = function() { if (Sbr.trigger) Sbr.last.className = 'sbrOptsCol'; Sbr.trigger = true; }
				this.childNodes[1].className = 'sbrOptsExp';
			} else {
				Sbr.lastObjId = false;
				document.onclick = function() {	}
				this.childNodes[1].className = 'sbrOptsCol';
			}
			if (this.childNodes[0].className == '') {
				this.nextSibling.focus();
			}
		}

		var curOpt = document.createElement('dt');
		curOpt.className = '';
		fauxSel.appendChild(curOpt);
		var optsWrap = document.createElement('dd');
		optsWrap.className = 'sbrOptsCol';
		fauxSel.appendChild(optsWrap);
		var optsList = document.createElement('ul');
		optsWrap.appendChild(optsList);
		optsList.style.zIndex = fauxSel.style.zIndex = 1000-counter;

		var opts = obj.options;
		var selectedOpt = (!obj.selectedIndex) ? 0 : obj.selectedIndex;
		for (var i=0; i<opts.length; i++) {
			var li = document.createElement('li');
			var txt = opts[i].text ? document.createTextNode(opts[i].text) : document.createTextNode('blank option');
			li.appendChild(txt);
			li.title = opts[i].title;
			li.selIndex = i;
			li.selectID = obj.id;
			li.onclick = function() {
				Sbr.selectMe(this);
			}
			if (i == selectedOpt) {
				li.className = 'sbrSelected';
				curOpt.appendChild(txt.cloneNode(false));
			}
			if (window.attachEvent) {
				li.onmouseover = function() {
					this.className += ' hover';
				}
				li.onmouseout = function() {
					this.className = this.className.replace(new RegExp(" hover\\b"), '');
				}
			}
			optsList.appendChild(li);
		}
		obj.oldonfocus = obj.onfocus;
		obj.onfocus = function() {
			if (this.oldonfocus) this.oldonfocus();
			this.previousSibling.childNodes[0].className = 'sbrFocused';
		}
		obj.oldonblur = obj.onblur;
		obj.onblur = function() {
			if (this.oldonblur) this.oldonblur();
			this.previousSibling.childNodes[0].className = '';
		}
		obj.oldonchange = obj.onchange;
		obj.onchange = function() {
			if(obj.previous == undefined) {
				obj.previous = obj.value;
			} else {
				if(obj.previous == obj.value) {
					return;
				} else {
					obj.previous = obj.value;
				}
			}
			/*alert("Change");*/
			if (this.oldonchange) this.oldonchange();
			var idx = this.selectedIndex;
			var ul = this.previousSibling.childNodes[1].childNodes[0];
			Sbr.selectMe(ul.childNodes[idx],1);
		}
		obj.onkeypress = obj.onchange;

		obj.parentNode.insertBefore(fauxSel,obj);
	},

	selectMe: function(liObj) {
		var selectElement = liObj.parentNode.parentNode.parentNode.nextSibling;
		var lis = liObj.parentNode.getElementsByTagName('li');
		for (var i=0; i<lis.length; i++) {
			if (lis[i] != liObj) {
				lis[i].className = '';
				lis[i].onclick = function() {
					Sbr.selectMe(this);
				}
			} else {
				this.setVal(liObj.selectID, liObj.selIndex);
				liObj.className = 'sbrSelected';
				var curOpt = liObj.parentNode.parentNode.parentNode.childNodes[0];
				curOpt.removeChild(curOpt.childNodes[0]);
				curOpt.appendChild(liObj.childNodes[0].cloneNode(false));
				if(arguments[1] != 1){
					selectElement.onchange();
				}
			}
		}
	},

	setVal: function(objID, val) {
		var obj = document.getElementById(objID);
		obj.selectedIndex = val;
	}
}

function writeStyles(styleFile){
	var headElement = document.getElementsByTagName("head")[0];
	var l=document.createElement("link");
	l.setAttribute("type","text/css");
	l.setAttribute("rel","stylesheet");
    var fullUrl = (designPath) ? designPath : '';
	l.setAttribute("href",fullUrl+"/"+styleFile);
	l.setAttribute("media","screen");
	headElement.appendChild(l);
}

/*write pager script to header function*/
function writeScript(url) {
    var headElement = document.getElementsByTagName("head")[0];

    /*var rnd = Math.round(Math.random()*999999);*/
    var fullUrl = (designPath) ? designPath : '';
	fullUrl += '/' + url; /*+ '?rnd=' + rnd;*/

    var sElement = document.createElement('script');
    sElement.setAttribute('type', 'text/javascript');
    sElement.setAttribute('charset', 'utf-8');
    sElement.setAttribute('src', fullUrl);
    
    headElement.appendChild(sElement);
}

/*New Vote*/
updateRating = function(voteObj) {
	$$('.vote_'+voteObj.cid).each(function(block){
		block.select('b').each(function(obj,index){
			if (index+1<=voteObj.voteTotal) obj.addClassName('active');
			else obj.removeClassName('active');
			if (index+1<=voteObj.voteUser) obj.addClassName('userRating');
			else obj.removeClassName('userRating');
			Event.stopObserving(obj, 'click');
			Event.observe(obj,'click',function(event){
				if (!voteObj.allowVoting) return;
				if (!window.userId || window.userId < 1) {document.location.href = (window.joinUrl) ? window.joinUrl : '/'; return}
				if (voteObj.disableVoting) {document.location.href = '/'; return;}
				var opt = {
					method: 'post',
					postBody: 'mode_ajax=true&UserVotes_action=userVote&UserVotes_cid='+voteObj.cid+'&UserVotes_vote='+(index+1),
					onSuccess: function(t) {
						var documentBody = document.getElementsByTagName('body')[0];
						var div = document.createElement('div');
						div.innerHTML = t.responseText;
						clearCache();
						documentBody.appendChild(div);
						voteObj.voteTotal = $F($('voteTotal_'+voteObj.cid));
						voteObj.voteUser = $F($('voteUser_'+voteObj.cid));
						window.updateRating(voteObj);
						documentBody.removeChild(div);
					},
					onFailure: function(t) {}
				}
				new Ajax.Request('uservotes.php?', opt);
				Event.stop(event);
			});
		});
	});
}

function formAjaxSubmit(form,params) {
	var upBlock = $(params.block+'_view');
	var uri = new Array();
	for (var i=0; i<form.elements.length; i++) {
		if (form.elements[i].type != 'radio' || form.elements[i].checked) uri.push(form.elements[i].name+'='+encodeURIComponent(form.elements[i].value));
	}
	uri = uri.join('&');
	var opt = {
		method: 'post',
		postBody: uri + '&mode_ajax=true',

		onSuccess: function(t) {
			var separator = '<!--'+params.module+'_content_separator-->';
			var respond = t.responseText.split(separator)[1];
			respond.evalScripts();
			upBlock.select('.opacity_block')[0].update(respond);
			initPagerListner(upBlock);
			upBlock.removeClassName('updating');
			window.setTimeout(function(){
				try {
					if (typeof createdPagesByPageLoaded == 'function') {createdPagesByPageLoaded(true);}
					Sbr.init(upBlock);
				} catch(e){}
			},200);
		},

		onFailure: function(t) {
			alert('Sorry, error in AJAX');
			upBlock.removeClassName('updating');
		}
	}
	
	upBlock.addClassName('updating');
	new Ajax.Request(params.module+'.php', opt);
	return false;
}

function applySearchByKeywords(event) {
	Event.stop(event);
	var link = Event.element(event);
	while (link.tagName.toLowerCase() != 'a') {
		link = link.parentNode;
	}
	var keyword = (/\s/.test(link.innerHTML)) ? '"' + link.innerHTML + '"' : link.innerHTML;
	if (!document.getElementById('input_helper_asist')) return;
	$('input_helper_asist').value = keyword;
	var helperForm = $('input_helper_asist').form;
	helperForm.scrollIntoView();
	try {
		changeEventAfterClick(event,'input_helper_div');
	} catch(e){}
	findAndCheck();
	var submitCode = helperForm.getAttribute('onsubmit') || helperForm.getAttribute('onSubmit') || false;
	if (typeof submitCode == 'function') eval('var submitResult = '+submitCode.toString().replace(/this/,'helperForm')+'();');
	else eval('var submitResult = ' + submitCode.replace(/return /,'').replace(/this/,'helperForm') +';');
	return submitResult;
}

function initSearchByKeyword() {
	var links = $A(Element.select($('scene_categories'),'a[rel]'));
	links.invoke('stopObserving', 'click', applySearchByKeywords);
	links.invoke('observe', 'click', applySearchByKeywords);
}

function initPagerListner(obj) {
	var obj = obj || document.documentElement;
	var links = $A(Element.select(obj,'.next_prev a','.scenes_list li a'));
	links.invoke('stopObserving', 'click', applyPagerClick);
	links.invoke('observe', 'click', applyPagerClick);
}

function applyPagerClick(event) {
	var link = Event.element(event);
	while (link.tagName.toLowerCase() != 'a') {
		link = link.parentNode;
	}
	var uri = link.href.split('?')[1];
	var queryParams = uri.toQueryParams();
	if (!link.rel) return;
	Event.stop(event);
	var params = link.rel.evalJSON();
	var upBlock = $(params.block+'_view');
	if (queryParams.Bi_cid) {
		var locationQuery = document.location.href.toQueryParams(), curSceneId = parseInt(document.location.hash.split('#')[1]);
		if ((locationQuery.Bi_cid && locationQuery.Bi_cid == queryParams.Bi_cid) || (!isNaN(curSceneId) && curSceneId == queryParams.Bi_cid)) {
			upBlock.scrollIntoView();
			return false;
		}
	}
	var opt = {
		method: 'post',
		postBody: uri + '&mode_ajax=true',
		
		onLoading: function(t) {
			try {
				if (queryParams.Bi_cid) {
					document.location.hash = '#' + queryParams.Bi_cid;
					upBlock.scrollIntoView();
				}
			} catch(e){}
		},

		onSuccess: function(t) {
			var separator = '<!--'+params.module+'_content_separator-->';
			var respond = t.responseText.split(separator)[1];
			//respond.evalScripts();
			upBlock.select('.opacity_block')[0].update(respond);
			initPagerListner(upBlock);
			upBlock.removeClassName('updating');
			window.setTimeout(function(){
				try {
					if (typeof createdPagesByPageLoaded == 'function') {createdPagesByPageLoaded(true);}
					Sbr.init(upBlock);
				} catch(e){}
			},200);
		},

		onFailure: function(t) {
			alert('Sorry, error in AJAX');
			upBlock.removeClassName('updating');
		}
	}
	
	upBlock.addClassName('updating');
	new Ajax.Request(params.module+'.php', opt);
	return false;
}

/*TEMP FOR helper*/
function changeEventAfterClick (event,element)
{
	Event.stop(event);
	var checkboxes = $$("#" + element + " input");
	var tmp = "*" + window.strip(element);
	for (c = 0; c<checkboxes.length; c++) {
		if (checkboxes[c].type == "checkbox" && checkboxes[c].className != "checkAll" && checkboxes[c].className != "checkAll checkFull") {
			var reg = (navigator.appName == "Microsoft Internet Explorer") ? window.p(checkboxes[c],1).innerText.substr(0, window.p(checkboxes[c],1).innerText.length-1) : window.p(checkboxes[c],1).textContent;
			if(tmp.toLowerCase().indexOf(reg.toLowerCase())>0) {
				checkboxes[c].checked = true;
				if (window.p(checkboxes[c],1).style.display != "block") {
					if(window.p(checkboxes[c],3).className.indexOf("opened")<0) {
						window.p(checkboxes[c],3).className += " opened";
					}
					window.p(checkboxes[c],2).style.display = "block";
					window.p(checkboxes[c],1).style.display = "block";
				}
			} else {
				checkboxes[c].checked = false;
				if (window.p(checkboxes[c],1).style.display == "block") {
					if(window.p(checkboxes[c],3).className.indexOf("opened")>0) {
						window.p(checkboxes[c],1).style.display = "none";
						if(!window.checkOpened(window.p(checkboxes[c],2))) {
							window.p(checkboxes[c],3).className = window.p(checkboxes[c],3).className.split(" ")[0] + " collapse";
							window.p(checkboxes[c],2).style.display = "none";
						}
					}
				}
			}
		}
	}
}


/*Switcher*/

function subsiteSwitcher() {
	$$('#subsite_switcher i').each(function(checkbox){
		var li = checkbox.up();
		if (li.lang == document.location.hostname.replace('www.','')) {
			li.addClassName('active');
			window.activeSwither = li;
		}
		Event.observe(checkbox, "click", function(event){
			/*checkbox = Event.element(event);*/
			var li = this.up();
			window.activeSwither.removeClassName('active');
			li.addClassName('active');
			window.activeSwither = li;
			var domainSplited = document.location.hostname.split('.');
			/*Set_Cookie( 'favSubDomain', li.lang, 30, '/', '.'+domainSplited[domainSplited.length-2]+'.'+domainSplited[domainSplited.length-1]);*/
			document.location.href = 'http://'+li.lang+'/';
		}.bind(checkbox));
	});
}

/*Keywords more*/
window.keywordsList = {
	keywords : new Array(),
	div : 'scene_categories',
	moreLink : '<span><a href="#" class="more_keywords_link" onclick="return showAllKeywords()">@text</a></span>'
};
function showAllKeywords() {
	var div = $(window.keywordsList.div);
	var p = div.down('p');
	p.update(window.keywordsList.keywords.join(' '));
	div.style.height = Element.getHeight(p) + 'px';
	initSearchByKeyword();
	return false;
}
function initKeywordsMore(moreText) {
	var div = $(window.keywordsList.div);
	div.addClassName('keysColp');
	var divHeight = Element.getHeight(div);
	var p = div.down('p');
	var pHeight = Element.getHeight(p);
	if (pHeight <= divHeight) {
		div.style.height = pHeight + 'px';
		//p.style.visibility = 'visible';
		initSearchByKeyword();
		return;
	}
	var spans = $A(p.getElementsByTagName('span'));
	var links = new Array();
	for (var i=0; i<spans.length; i++) {
		links.push(Element.inspect(spans[i]) + spans[i].innerHTML + '</' + spans[i].tagName.toLowerCase() + '>');
	}
	window.keywordsList.keywords = links.clone();
	var moreLink = window.keywordsList.moreLink.replace('@text',moreText);
	var flag = false;
	while (!flag) {
		links.pop();
		p.update(links.join(' ') + ' ' + moreLink);
		pHeight = Element.getHeight(p);
		if (Element.getHeight(p) <= divHeight) flag = true;
	}
	div.style.height = pHeight + 'px';
	//p.style.visibility = 'visible';
	initSearchByKeyword();
}

document.observe("dom:loaded", function() {
	Sbr.init();
	initPagerListner();
});

/*send Content Error*/
function sendContentError(obj) {
	var obj = obj || new Object();
	var data = {
		code : obj.code || 404,
		url : obj.url || null
	}
	var frame = document.createElement('iframe');
	with (frame) {
		src = document.location.protocol + '//' + document.location.host + '/logError/contentError.html?code=' + data.code + (data.url ? '&url='+escape(data.url) : '');
		with (style) {
			position = 'absolute';
			top = '-10000px';
			left = '-10000px';
			width = '0';
			height = '0';
			visibility = 'hidden';
		}
		var handler = function(){document.body.removeChild(frame);};
		if (document.addEventListener) addEventListener('load', handler, false)
		else attachEvent('onload', handler);
	}
	document.body.appendChild(frame);
}

/* hides 'splash' div and sets cookie 'cms_splash_screen' about it */
function hideSplash() {
	expires = 365; // days

	var today = new Date();
	today.setTime( today.getTime() );
	var expires_date = new Date( today.getTime() + (expires * 1000 * 60 * 60 * 24) );
	document.cookie = 'cms_splash_screen=1' + ';expires=' + expires_date.toGMTString();

	$('splash_out').style.display = 'none';
	$('splash').style.display = 'none';

}
