/**
 * @author Szymon
 */
/**
 * @author Szymon
 */

var config = {
	imgPath:'../images/',
	jsPath:'./exec/clientsite/codexd/',
	jsSufix:'core'
};
var lang = 'pl'
var loaded = false;
var w18 = null;
var nFr = null;	
var newsV = null;
var regwnd;

var JSLinks;

document.ready(function(){
			//loaded = codexd.loadMoules({modules:['ajax','json','cookie','lang']});
		 //window.TID = window.setInterval(
			//function(){
			//	if(loaded){
					//lang = (codexd.empty(cookies.getCookie(langCore.cookieName)))?'pl':cookies.getCookie(langCore.cookieName);
					//langCore.enableLang(lang);
						//codexd.$cc('NotifyForm').style.background = 'url(./exec/images/layout/notify/regin_'+lang+'.png)';
						//document.title = jsonT.title[lang];
						window.lang = 'pl';
					w18 = msgi18n[window.lang];				
					//bRf(); bDf();bCf();
					//window.clearInterval(window.TID);
			//	}
		//	},5);
		
		if(cookies.getCookie('infoWnd_conf')){
			buildNewsWnd();
		}
		if(cookies.getCookie('shoutWnd_conf')){
			shoutWnd();
		}
		if(cookies.getCookie('ruleWnd_conf')){
			buildRuleWnd();
		}
		spotWnd();
		//buildIframeWnd();
		JSLinks = getLinks();
		lInterpeter();
		
		window.setInterval(function(){new callReq({url:'ajax.php?checkDel=true'});},1000);
	
});

		function lInterpeter(){
			if(JSLinks[0] == 'active'){
				new callReq({
					url:'ajax.php?active='+JSLinks[0]+'&mail='+JSLinks[1]+'&keyid='+JSLinks[2]+'',
					target:'statusBar'
				});
			}
			
		}

		function buildNewsWnd(){
			new newWnd({prefix:'info',wndC:'infoWnd wndPos',expand:true});  
			newsV = new newsView({newsParent:'infoContentWnd',prefix: 'newsV',sNum:10,slideshow:true}); 
			codexd.$cc('infoHeadWnd').innerHTML = jsonT.info.head[window.lang];
		}
		
		function buildIframeWnd(){
			new newWnd({prefix:'iframe',wndC:'infoWnd wndPos',expand:true});  
			codexd.$cc('iframeContentWnd').innerHTML = "<iframe width='100%' height='100%' frameborder='0' src='http://onet.pl'></iframe>";
			codexd.$cc('iframeHeadWnd').innerHTML = "Iframe";
		}
		
		function buildReginWnd(){
			regwnd = new newWnd({prefix:'regin',wndC:'ruleWnd wndPos',expand:true});  
			codexd.$cc('reginHeadWnd').innerHTML = jsonT.regin.head[window.lang];
			codexd.$cc('reginContentWnd').appendChild(ruleCont());
			codexd.$cc('ruleCont').appendChild(buildRules(window.lang,'rulesListReg'));
			bRf();
		}
		
		function buildRuleWnd(){
			new newWnd({prefix:'rule',wndC:'ruleWnd wndPos',expand:true,contWC:"ruleContText"});
			codexd.$cc('ruleContentWnd').appendChild(buildRules(window.lang,'rulesList')); 
			codexd.$cc('ruleHeadWnd').innerHTML = jsonT.rule.head[window.lang];
		}
		
		function shoutWnd(){
			new newWnd({prefix:'shout',wndC:'shoutWnd wndPos',expand:true});
			codexd.$cc('shoutContentWnd').innerHTML = "<div id=\"yshout\"></div><a id=\"ys-history-link\" class=\"ys-post-form-link\" href=\"/exec/plugins/history/?log=1\"></a>";
			codexd.$cc('shoutHeadWnd').innerHTML = "ShoutBox";//jsonT.rule.head[window.lang]; 
			new YShout({yPath: './exec/plugins/yshout',yLink: 'rars'});	
		}

		function spotWnd(){
		new newWnd({prefix:'spot',wndC:'spotWnd wndPos',expand:true});
			codexd.$cc('spotContentWnd').innerHTML = '<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/zjK2oSYTYbA&amp;hl=pl_PL&amp;fs=1?color1=0x3a3a3a&amp;color2=0x999999"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/zjK2oSYTYbA&amp;hl=pl_PL&amp;fs=1?color1=0x3a3a3a&amp;color2=0x999999" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object>';
			codexd.$cc('spotHeadWnd').innerHTML = "Spot Reklamowy";//jsonT.rule.head[window.lang]; 
				
		}
			
			function bRf(){
				var nFr = new newForm({msg:'',cont:'ruleForm',name:'rulesForm',id:'rulesForm',action:'?',method:'POST'});
					nFr.fld({msg:w18.fields.acc,name:'accept',id:'accept',type:'checkbox',onchange:'afterAccept(this);',value:'1',r:1});				
			}
			
			function clearRulesForm(){
				var cont = document.getElementById('ruleFrame');
				var chlds = cont.childNodes;
				for (var i = 0; i < chlds.length; i++) {
					codexd.$cc('ruleFrame').removeChild(chlds[i]);
				}
				
				var cont = document.getElementById('ruleForm');
					if (cont != null) {
						var chlds = cont.childNodes;
						for (var i = 0; i < chlds.length; i++) {
							codexd.$cc('ruleForm').removeChild(chlds[i]);
						}
					}else{
					var rFrame =  document.getElementById('ruleFrame'); 
					var ruleForm = document.createElement('div');
						ruleForm.id = "ruleForm";
					rFrame.appendChild(ruleForm);
					}
			}

			function afterAccept(){
				var reg = arguments[0];
				if(reg.checked){
					clearRulesForm();
					//bDf();	
					uCf();				
				} 
			}
			
			function removeHTMLTags(strInputCode){
			 	 	strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
			 		 	return (p1 == "lt")? "<" : ">";
			 		});
			 		var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
					return strTagStrippedText;
			}
			
			function getLabels(){
				var field = arguments[0];
				var labels = document.getElementsByTagName('label');
					for(var i=0;i<labels.length;i++){
						if(labels[i].htmlFor == field.id){
							return removeHTMLTags(labels[i].innerHTML.replace("*",""));
						}else{
							continue;
						}
					}
			}
			
			function saveData(){
				var form = arguments[0].form;
				var els = form.elements;
				var save = false;
				var	data = {};
				var fields = {};
					for(var i=0;i<els.length;i++){
						if(els[i].type != 'button' && els[i].type != 'submit'){
							els[i].focus();							
							if(els[i].value != ''){								
								save = true;
								data[els[i].name] = els[i].value;
								fields[els[i].name] = {};
								fields[els[i].name].value = els[i].value;
								fields[els[i].name].label = getLabels(els[i]);								
							}else{
								save = false;
								break;
							}
						}
					}
				if(save){
					if (cookies.getCookie('notifyStart')) {
						var notifyStart = eval("(" + (cookies.getCookie('notifyStart').replace(/\"/g, "'") + ")"));
						notifyStart.usrData = data;
						cookies.setCookie("notifyStart",toJsonString(notifyStart),60,1);
					}
						//fields['fileName'].label = 'Plik';
						//fields['fileName'].value = notifyStart.fileName;
						cookies.setCookie("fields",toJsonString(fields),60,1);
					summaryNotify();										
				}
			
			}
			
			function summaryNotify(){
				
				var bf = document.createElement('fieldset');
				bf.id = "summary_fieldset";
				var fl = document.createElement('legend');
				fl.innerHTML = 'Podsumowanie Zgloszenia';	
				bf.appendChild(fl);
				var notifyFields = {};
				if (cookies.getCookie('fields')) {
					notifyFields = eval("(" + (cookies.getCookie('fields').replace(/\"/g, "'") + ")"));
				}
					for(var i in notifyFields){
					var dt = document.createElement('dt');
					var dd = document.createElement('dd');
					var dl = document.createElement('dl');
						bf.appendChild(dl);
						dt.innerHTML = notifyFields[i].label;
						dd.innerHTML = notifyFields[i].value;
						dl.appendChild(dt);
						dl.appendChild(dd);
					}
				clearRulesForm();
				codexd.$cc('ruleForm').appendChild(bf);	
				var nFd = new newForm({msg:'',cont:'ruleForm',name:'dataForm',id:'dataForm'});
				nFd.btn({name: 'sender',msg:'Popraw',onclick:'bDf(this);'});	
				nFd.btn({name: 'sender',msg:'Zatwierdź',onclick:'saveSummary(this);'});	
			}
			
			function saveSummary(){
				if (cookies.getCookie('notifyStart')) {
					var notifyStart = eval("(" + (cookies.getCookie('notifyStart').replace(/\"/g, "'") + ")"));
					new callReq({
						method: 'p',
						url:'ajax.php?makeNotify=true',
						HP: notifyStart
					});
				}
			}
			
			function bDf(){
				clearRulesForm();
				var data = {};
				if (cookies.getCookie('notifyStart')) {
					var notifyStart = eval("(" + (cookies.getCookie('notifyStart').replace(/\"/g, "'") + ")"));
					data = codexd.defined(notifyStart.usrData)?notifyStart.usrData:{};				
				}
				
				var nFd = new newForm({msg:w18.fields.dF,cont:'ruleForm',name:'dataForm',id:'dataForm'});
					nFd.fld({msg:w18.fields.nick,name:'nick',id:'nick',type:'text',r:1,value:(codexd.defined(data.nick)?data.nick:'')});
					nFd.fld({msg:'Plec',name:'sex',id:'sex',type:'select',r:1,def:(codexd.defined(data.sex)?data.sex:''),dict:[{value:'0',text:'Mezczyzna'},{value:'1',text:'Kobieta'}]});
					nFd.fld({msg:w18.fields.email,name:'mail',id:'mail',type:'text',onvalid:'checkmail',r:0,im:1,value:(codexd.defined(data.mail)?data.mail:'')});
					nFd.fld({msg:w18.fields.amvName,name:'AmvName',id:'AmvName',type:'text',r:1,value:(codexd.defined(data.AmvName)?data.AmvName:'')});
					nFd.fld({msg:w18.fields.amvDesc,name:'AmvDesc',id:'AmvDesc',type:'desc',r:1,value:(codexd.defined(data.AmvDesc)?data.AmvDesc:'')});
					nFd.btn({name: 'reup',msg:'Przeslij ponownie',onclick:'uCf(this);'});
					nFd.btn({name: 'sender',msg:'Dalej >>',onclick:'saveData(this);'});
					
			}
			
			function checkmail(e){
				var f = this;
				if(f.value == ''){
					var vm = new callReq({
							     method: 'p',
						    	 url:'ajax.php?mch=true',
						    	 HP: {mail:f.value}
					        });
				}
			}
			
			function uCf(){
				clearRulesForm();
				var nFc = new newForm({msg:"Przeslij teledysk",cont:'ruleForm',name:'uploadForm',id:'uploadForm',action:'#',method:'POST'});					
				if (cookies.getCookie('notifyStart') && !codexd.defined(arguments[0])) {
					var notifyStart = eval("(" + (cookies.getCookie('notifyStart').replace(/\"/g, "'") + ")"));
					notifySessionInfo(notifyStart.fileName);
				}else{					
					codexd.$cc("uploadForm_fieldset").appendChild(bUpCont());
					var settings = {
						flash_url: "./exec/plugins/swf_uploader/swfupload.swf",
						upload_url: "./exec/serversite/php/upload_class.php",
						file_size_limit: "100 MB",
						file_types: "*.avi;*.mp4;*.mkv;*.mpg4;*.mpg;*.rmvb;*.mov",
						file_types_description: "Pliki Video",
						file_upload_limit: 1,
						//file_queue_limit : 0,
						
						debug: false,
						
						// Button settings
						button_image_url: "exec/plugins/swf_uploader/images/send.png",
						button_width: "67",
						button_height: "22",
						button_placeholder_id: "uploadBtn",
						
						moving_average_history_size: 40,
						
						// The event handler functions are defined in handlers.js
						file_queued_handler: fileQueued,
						file_dialog_complete_handler: fileDialogComplete,
						upload_start_handler: uploadStart,
						upload_progress_handler: uploadProgress,
						upload_success_handler: uploadSuccess,
						upload_complete_handler: uploadComplete,
						
						custom_settings: {
							tdFilesQueued: document.getElementById("ddFilesQueued"),
							tdFilesUploaded: document.getElementById("ddFilesUploaded"),
							tdErrors: document.getElementById("ddErrors"),
							tdCurrentSpeed: document.getElementById("ddCurrentSpeed"),
							tdAverageSpeed: document.getElementById("ddAverageSpeed"),
							tdMovingAverageSpeed: document.getElementById("ddMovingAverageSpeed"),
							tdTimeRemaining: document.getElementById("ddTimeRemaining"),
							tdTimeElapsed: document.getElementById("ddTimeElapsed"),
							tdPercentUploaded: document.getElementById("ddPercentUploaded"),
							tdSizeUploaded: document.getElementById("ddSizeUploaded")
						}
					};
					
					var swfu = new SWFUpload(settings);
				}
			}
			
			function bCf(){
				var nFc = new newForm({msg:w18.fields.cF,cont:'ruleForm',name:'confirmForm',id:'confirmForm',action:'?',method:'POST'});
					nFc.fld({msg:'Code',name:'confirmCode',id:'confirmCode',type:'text',nl:1,r:1});
					nFc.btn({submit:1,name:'confirm',msg:'Confirm'});	
			}
			
			function ruleCont(){
				var rFrame = document.createElement('div');
					rFrame.id = "ruleFrame";					
				var ruleCont = document.createElement('div');
					ruleCont.id = "ruleCont";
				var ruleTitle = document.createElement('h2');
					ruleTitle.id = "ruleTitle";
					ruleTitle.innerHTML = jsonT.rule.head[window.lang];
				var ruleForm = document.createElement('div');
					ruleForm.id = "ruleForm";
				rFrame.appendChild(ruleCont);
					ruleCont.appendChild(ruleTitle);
				rFrame.appendChild(ruleForm);
					
				return rFrame;
			}
			
			function bUpCont(){
				var flCont = document.createElement('div');
					flCont.id = "uploadContDiv";
				var span = document.createElement('span');
					span.id="uploadBtn";
					flCont.appendChild(span);
				var tbl = document.createElement('table');
					tbl.align = "center";
				var setArr = {ddFilesUploaded:"",
							  ddSizeUploaded:"Wysłany rozmiar",
							  ddPercentUploaded:"Procent",
							  ddTimeElapsed:"Czas, jaki upłynął",
							  ddTimeRemaining:"Przewidywany czas",
							  ddAverageSpeed:"Średnia predkosc",
							  ddMovingAverageSpeed:"",							  
							  ddCurrentSpeed:"",
							  ddFilesQueued:"",
							  ddErrors:"Błedy"							  
							  };
					for(var i in setArr){
						var tr = document.createElement('tr'); 
						var dt = document.createElement('th');
						var dd = document.createElement('td');
							dt.innerHTML = setArr[i];
							dd.id = i;
							if(i=='ddMovingAverageSpeed' || i=='ddCurrentSpeed' || i=='ddFilesQueued' || i =='ddFilesUploaded'){
								dd.style.display = "none";
								dt.style.display = "none";
							}
							tr.appendChild(dt);												
							tr.appendChild(dd);
							tbl.appendChild(tr);
					}	
					flCont.appendChild(tbl);			
				return flCont;
			}
			
			
			function notifySessionInfo(){
				if (!arguments[0]) {
					alert("Przeslany plik bedzie przetrzymywany na serwerze przez 1 godzine.\n" +
						"Po tym czasie jesli nie nastapi zakonczenie zgloszenia\n" +
						"plik bedzie automatycznie usuniety a zgloszeni anulowane!");						
				if (cookies.getCookie('notifyStart')) {
					var notifyStart = eval("(" + (cookies.getCookie('notifyStart').replace(/\"/g, "'") + ")"));
					new callReq({url:'ajax.php?setFroDel=true&fileName='+notifyStart.fileName});
				}	
					clearRulesForm();
					bDf();
				}else{
					alert("Przeslany plik "+arguments[0]+" jest jeszcze aktualny!");
	    			clearRulesForm();
					bDf();
				}										
			}			
			
/*window.onload = function(){
	codexdCore.loadMoules({
		ajax:"ajax",
	});	
};*/
