/**
 * TvProfil Core javascript engine
 * TvProfil.net (c), Mediaking.hr (tm)
 * Author: kowach@gmail.com
 * Year: 2010
 *
 */

var Tools = {
	get: function(url,data)
	{
		Tools.loader();
		$.get(url,data,function(d){ Tools.open(d); });
	},
	open: function(data, p)
	{
		if(p==null)
			pos = Core.locate($('#tools'));
		else
			pos = p;
		// postavi background
		$('#toolsBg').css({
			height: $(document).height(),
			width: $(document).width(),
			display:'block',
			opacity:0.3
		});
		$('#tools').html(data);
		$('#tools').css({
			left:pos.L,
			top:pos.T,
			width:pos.W,
			height:0,
			display:'block',
			opacity:0.3
		});
		Tools.resize('tools',p);
	},
	// resajza prozor da svi elementi budu vidljivi
	resize:function(id, p)
	{
		var e = $('#'+id);
		var pos = Core.locate(e);

		if(e.is('div')) {
			var maxW=pos.W;
			var maxH=pos.H;
			$('#'+id+' *').each(function(){
				if($(this).outerWidth()>maxW) maxW=$(this).outerWidth();
				if($(this).outerHeight()>maxH) maxH=$(this).outerHeight();
			}); // find max width
			pos.W=maxW+10; // postavlja najvecu sirinu ako je veca
			pos.H=maxH; // postavlja najvecu visinu ako je veca

			if(pos.W+pos.L>$(document).width()) pos.L=$(document).width()-pos.W-10; // ako ispada s desne strane, onda ga povuci
			if(pos.L<0) pos.L=0;
			if(p==null)
				pos.L=($(document).width()-pos.W)/2;
			if(p==null)  {
				pos.T=($(window).height()-pos.H)/2;
				if(pos.T<=0) pos.T=50;
				pos.T = pos.T+$(window).scrollTop();
			}
			// bez animacija prozora anim=1
			if (TV.anim==1) {
				e.css({top: pos.T, left: pos.L, height:pos.H+10, width:pos.W+10, opacity:1 });
				$('#toolsBg').css({
					height: $(document).height(),
					width: $(document).width()
				});
			}else {
				e.animate({top: pos.T, left: pos.L, height:pos.H, width:pos.W, opacity:1 }, 0, 'linear', function(){
					$('#toolsBg').css({
						height: $(document).height(),
						width: $(document).width()
					});
				});
			}
		} else {
			alert('resize: no div '+id);
		}

	},

	/**
	 * Ajax loader
	 */
	loader:function()
	{
		$('#tools').css({
			left:($(document).width()-200)/2,
			top:($(window).height()-200)/2+$(window).scrollTop(),
			width:200,
			height:50,
			display:'block',
			opacity:1
		});
		$('#tools').html('<div id="innerTools"></div>');
		Core.putLoader($('#innerTools'));
	},

	/**
	 * Da li treba upozorit prijezatvaranja
	 */
	toolsCloseWarnig:true,

	close: function()
	{
		if(arguments.length==1) {
			if(arguments[0]==true) if(confirm("Exit?")==false) return false;
		}
		else if( Core.toolsCloseWarnig == true ) {
			if(confirm("Exit?")==false) return false;
		}

		$('#toolsBg').css({
			width:0,
			height:0,
			display:'none'
		});

		var t=$('#tools');

		//if(t.css('display')=='none') return tru;

		t.animate({opacity:0 });
		t.css({
			width:0,
			height:0,
			display:'none'
		});

		return true;
	}
};

var Core = {

	dargY:0,
	dargX:0,
	dragging:null,
	dragLoc:null,
	taregt:null,

	// Set language and reload pae
	chLang: function(lang){
		document.location='/?setlang='+lang.value;
	},


	/**
	 * Submits a form
	 */
	submit: function(form){
		$('#'+form).submit(function(d){ Tools.open(d); }, Tools.loader());
		return false;
	},


	/**
	 * Resortira retke u tablici, renumerira sve input elemente
	 */
	resort: function(e,sortInput,direction){
		if(direction=='up') e.after(e.prev()); else e.before(e.next());
		$('input[name*='+sortInput+']').each(function(k,i){ $(i).val(k+1); });
	},

	locate: function( elem ){ // return { L:left, R:right, T:top, B:bottom, H:height, W:width }
		var $el = $(elem), pos = $el.offset(), h = $el.outerHeight(), w = $el.outerWidth();
		return { elem: elem, L: pos.left, R: pos.left+w, T: pos.top, B: pos.top+h, W: w, H: h };
		},
	// test the location positions of an element against another OR an X,Y coord
	contains: function( target, test ){ // target { L,R,T,B,H,W } contains test [x,y] or { L,R,T,B,H,W }
		return ( ( test[0] || test.L ) >= target.L && ( test[0] || test.R ) <= target.R
			&& ( test[1] || test.T ) >= target.T && ( test[1] || test.B ) <= target.B );
	},

	init: function()
	{
		if(TV.datum=='') {
			var d=new Date();
			TV.datum=d.getFullYear()+'-'+(d.getMonth()+1<10?'0':'')+(d.getMonth()+1)+'-'+(d.getDate()<10?'0':'')+d.getDate();
		}


		// Inicijalizacija evenata na All i My Channels
		$('.chtab div')
			.bind('mouseover',function(){ $(this).addClass('tv_dani2'); })
			.bind('mouseout',function(){ $(this).removeClass('tv_dani2'); });
		$('#myKanal')
			.bind('click',function( event ){
				$('.chtab div').removeClass('tv_dani3');
				$(this).addClass('tv_dani3');
				TV.setPaket(-1, null);
			});
		$('#paket')
			.bind('click',function( event ){
				$('.chtab div').removeClass('tv_dani3');
				$(this).addClass('tv_dani3');
				TV.setPaket(TV.paketID, null);
		});
		// meni za biranje drugih paketa
		$('#paketSelector')
			.bind('mousedown',function( event ){
				Tools.loader();
				var pos = Core.locate( $('#paket') );
				$.get("/tool/package.php",{  }, function(data){
					Tools.open(data, pos);
					Core.hover('pkglist');
					});

		});


		// zatvarenj toolsa na klik izvan prozora
		$('#toolsBg').bind('mousedown',function( event ){ Tools.close(); });


		// phazerbox movable eventi
		$('.phbox')
			.bind('dragstart',function( event ){
				if( $(event.target).is('.phdrag') )
				{
					clearTimeout( TV.saveTimeoutID );
					Core.dragY=event.offsetY;
					Core.dragX=event.offsetX;
					Core.dragLoc=Core.locate(this);
					$( this ).addClass('phbox_drag');
					$( this ).css({opacity:0.9});
					Core.dragging = this;
					return true;
				}
            	return false;
            })
			.bind('dragend',function( event ){

				e=$(this);
				t=$('.phbox_target');
				y=0;x=0;
				if(t.length>0){
					tt=Core.locate(t);
					x=tt.L-Core.dragX;
					y=tt.T-Core.dragY;
					//TV.saveTimeoutID = setTimeout("TV.saveChannelPos();", 3000); // Save delay
					TV.saved=false;
					//TV.setChannelPos();
					setTimeout("TV.setChannelPos()", 1000);
				}
				$( this ).animate({ top:y, left:x, opacity:1 },function(){
					e.removeClass('phbox_drag');
					t.removeClass('phbox_target');
					t.css({opacity:0.4});
					if(t.length>0){
						p=e.prev('.phbox');
						n=e.next('.phbox');
						t.before( e );
						if(p.length>0) {
							if( t.attr('rel')!=p.attr('rel') ) p.after( t );
						}
						else if(n.length) {
							if( t.attr('rel')!=n.attr('rel') ) n.before( t );
						}
						e.css( {top:0, left:0} );
						t.animate({ opacity:1 });
					}

				}) ;

            })
            .bind('drag',function( event ){
            	e=this; //element koji se povlaci

            	proxy = Core.locate(e);

            	$('.phbox').each(function(){
            		Core.target=Core.locate(this); // moguci box iznad kojeg se nalazimo

            		if( e==this ) { // sam iznad sebe - nista

            		} else if( Core.contains( Core.target, [ proxy.L+proxy.W/2, proxy.T+proxy.H/2 ] ) ) {
            			$(this).addClass('phbox_target');
            		} else {
            			$(this).removeClass('phbox_target');
            		}
            	});


                $( this ).css({
                        top: event.offsetY-Core.dragY,
                        left: event.offsetX-Core.dragX
                        });

			});


	},


	initTopMenu: function(){
		$('#mk-menu li').each(function(){
			$(this).mouseover ( function () { $(this).addClass('mk-hover');  } );
			$(this).mouseout ( function () { $(this).removeClass('mk-hover');  } );
		});
	},
	initChannelMenu: function(){

		$('.kn_mitems>div').each(function(i){
			if( TV.kanalID == $(this).attr('rel') )  {
				$(this).parent().parent().addClass('current');
				$(this).addClass('kn_mitem_sel');
			}

			//zasivi svaki drugi item
			//if(i%2==0) $(this).addClass('kn_mitem2');

			$(this).mouseover ( function () { $(this).addClass('kn_mitem_hover');  } );
			$(this).mouseout ( function () { $(this).removeClass('kn_mitem_hover');  } );
			$(this).click ( function () {
				if(Core.dragY>0) {
					Core.dragY=0;
					return;
				}
				TV.kanalID=parseInt($(this).attr('rel'));
				TV.setTitle($(this).attr('title'));
				$('.kn_mitems>div').removeClass('kn_mitem_sel');
				$(this).addClass('kn_mitem_sel');
				//location.hash=$(this).attr('href');
				TV.loadProgram( );
			} );

			if(TV.myKanal==1) {

			// animacija i promjene pozicija knala
			$(this)
				.bind('dragstart',function( event ){
				if( $(event.target).is('.kn_rupe') )
					{
						clearTimeout( TV.saveTimeoutID );
						Core.dragY=event.offsetY;
						$( this ).addClass('kn_mitem_drag');
						$( this ).css({zIndex: 100, opacity:0.8,left: 1});
						return true;
					}
                	return false;
                })
				.bind('dragend',function( event ){
					//TV.saveTimeoutID = setTimeout("TV.saveChannelPos();", 3000); // Save delay
					TV.saved=false;
					//setTimeout("TV.setChannelPos();", 3000);
					setTimeout("TV.setChannelPos()", 1000);

					$( this ).removeClass('kn_mitem_drag');
					$( this ).css({zIndex: 1});
					$( this ).animate({top:0, left: 0, opacity:1 });
					//Core.dragY=0;

                })
                .bind('drag',function( event ){
					e=this; //element koji se povlaci
					off=Math.round(Math.floor((event.offsetY-Core.dragY)/12)/2); // pomaknut broj elemenata od trenutnog

					var cur=0;
					$('.kn_mitems>div').each(function(i){
						if(e==this)	cur=i; // nasao povucni element
					});

					$('.kn_mitems>div').each(function(i){
						//$('#test').html("off="+off+",cur="+cur+",i="+i);
						if( cur+off==i && this!=e ) {
							if(off<=0){
								$(this).before( e );
								Core.dragY-=24;
							} else {
								$(this).after( e );
								Core.dragY+=24;
							}
						}
					});
	                $( this ).css({
	                        top: event.offsetY-Core.dragY
	                        });
	                });
				}

		});

		Core.initChannelItems();

		//zasivi odabrani tab
		$('.chtab div').removeClass('tv_dani3');
		if(TV.myKanal==1) $('#myKanal').addClass('tv_dani3'); else $('#paket').addClass('tv_dani3');

		// pokreni accordion
		$('#kn_menu').accordion();

	},

	initChannelItems: function(){
		$('.kn_mitems>div').each(function(i){
			if(i%2==0) $(this).addClass('kn_mitem2'); else $(this).removeClass('kn_mitem2');
		});
	},
	initDayMenu: function(){
		$('#day_menu span').each(function(){
			$(this).mouseover ( function () { $(this).addClass('tv_dani2');  } );
			$(this).mouseout ( function () { $(this).removeClass('tv_dani2');  } );
			$(this).click ( function () {
				TV.datum=$(this).attr('rel');
				TV.setDateTitle($(this).attr('title'));
				$('#day_menu span').removeClass('tv_dani3');
				$(this).addClass('tv_dani3');
				TV.loadProgram( );
			} );
			// odaberi datum

			//alert(TV.datum); alert($(this).attr('rel')); return false;
			if( TV.datum == $(this).attr('rel') )$(this).addClass('tv_dani3');
		});
	},

	/**
	 * Treba se pozivati na
	 *   - glavnom listingu
	 *   - trazlici
	 *   - i svuda gdje postoji alarm-sat
	 */
	initTvListing: function(){
		// postavlja fav zvjezicu
		var usrchn = ','+TV.kanalFav+',';
		if(usrchn.indexOf(','+TV.kanalID+',')>-1) $('#favKanal').addClass('star_full');

		// Inicijalizira tool tip i evente za alarm
		$(".tv_table a[title!='']").tooltip({
	        tip: '#tooltip',
	        effect: 'fade',
	        offset: [0, 330],
	        fadeInSpeed: 10,
	        fadeOutSpeed: 100,
	        predelay: 400,
	        lazy:false,
	        position: ['bottom', 'left']
	    }).dynamic( {
	        top: {
	    		direction: 'up',
	            bounce: true
	        }
	    });

		// inicijalizire evente na alarm tooltipu
		Core.hover('alarm');
		if(TV.anim==0)
		$(".alarm").tooltip({
					tip: '#alarmtip',
			        effect: 'fade',
			        fadeInSpeed: 30,
			        fadeOutSpeed: 0,
			        predelay: 900,
			        position: ['top', 'left'],
			        lazy:false,
			        onBeforeShow:function(){ this.getTip().html($('#alarmMsg').html()); }
			    });

		$(".alarm").fixClick(
		    		function( ){
		    			// on click
						Tools.loader();
						$.post('/tool/alarm.php',{ kanalID:TV.kanalID,tm:$(this).parent().attr('rel')  }, function(d){ Tools.open(d,null); });
					},function( ){
						// doubleclick
						if($(this).hasClass('alarmone'))
							$.post('/tool/alarm.php',{ action:'delalarm',aopt:2,kanalID:TV.kanalID,tm:$(this).parent().attr('rel')  }, function(d){ Tools.open(d,null); });
						else if( !$(this).hasClass('alarmfav'))
							$.post('/tool/alarm.php',{ action:'setalarm',aopt:2,achkmail:'true',achksms:'false',kanalID:TV.kanalID,tm:$(this).parent().attr('rel')  }, function(d){ Tools.open(d,null); });
					}

			    );
		if(TV.editor==1) {
			$(".alarm").after('<td class="editor"></td>');
			$(".editor").bind('click',function( event ){ Tools.get('/tool/tvshow.edit.php', {data:$(this).parent().attr('rel')}); } );
			Core.hover('editor');
		}

		Core.initAlarm();
		Core.setCurrentShow();

	},

	// konfiguracija: moji kanali
	myChannels: function()
	{
		Tools.loader();
		$.get("/tool/channel.php",{ opt:'my' }, function(data){
			Tools.open(data);
			$('.channelsConf>div>label')
				.bind('mouseover',function( event ){ $(this).addClass('chnConfItem'); })
				.bind('mouseout',function( event ){ $(this).removeClass('chnConfItem'); })
				.bind('click',function( event ){ if($(this).children('input').is(':checked')) $(this).addClass('chnConfItemMy'); else $(this).removeClass('chnConfItemMy');  });
		});
	},
	// snima moje kanale
	saveMyChannels: function()
	{
		var arr=$('.channelsConf (input[type=checkbox]):checked').map(function(){ return $(this).val(); });
		if(arr.size()>100) {
			alert('Dozvoljeno je maksimalno 100 kanala!');
			return;
		}

		Core.putLoader($('#toolsBody'));
		TV.kanalFav=$.makeArray(arr).join(',');
		$.post("/mode/mode.tv.kanali.php",{ myChannels:TV.kanalFav , save:1 }, function(data){
			TV.setPaket('-1',$('#toolTitle').html());
		});
		if($('#tab_trenutno').length>0) TV.loadTrenutno('', 0);

	},

	setCurrentShow:function()
	{
		// curent unix timestamp
		var ut=parseInt(new Date().getTime().toString().substring(0, 10));

		// dinamicki oznacava trenutnu emisiju - mora postojati rel atribut "unix_timestamp,length"
		if($(".tv_table").length>0){
			$(".current_track").remove();
			$(".currently").removeClass('currently');
		}
		$(".tv_table tr").each(function(){
			var d=$(this).attr('rel');
			if(!d) return;
			var a=d.split(/,/);
			var b=parseInt(a[0]);
			var c=parseInt(a[1]);
			if(b<=ut && ut<b+c) {
				$(this).addClass('currently');
				var currently_p=Math.round((ut-b)/c*100);
				$(this).after('<tr class="current_track"><td colspan="'+$(this).find('td').size()+'"><div class="currtrack"><div style="width:'+currently_p+'%"></div></div></td></td>');
			}
		});
	},
	/**
	 *  Ucitava nove alarme u internu varijablu TV.alarmData i poziva potrebne inite alarma
	 */
	loadAlarmData:function()
	{
		$.getJSON("/tool/alarm.php",{my:"get",kID:0}, function(data){TV.alarmData=data; Core.initAlarm(); TV.alarmBox(); });
	},
	/**
	 * Prolazi kroz sve alarm-satove i oznacava zelene
	 */
	initAlarm: function()
	{
		$('.alarm').each(function(){
			$(this).removeClass('alarmfav alarmone');
		});
		$.each(TV.alarmData, function(i,item){
			var kID=TV.kanalID;
			$('.alarm').each(function(){
				var d=$(this).parent().attr('rel');
				if(!d) return;
				var a=d.split(/,/);
				if(a[2]) kID=a[2];

				if ( a[0] == item.ts && kID == item.kid ) {
					if(item.ty=="1") $(this).addClass('alarmfav');
					if(item.ty=="2") $(this).addClass('alarmone');
				}

			});
          });
	},
	/**
	 * Postavlja click na kalendar za odabir tv programa
	 */
	initCalendar: function()
	{
		$('#inner_calendar .day').bind('click',function( event ){
			TV.setDateTitle($(this).attr('title'));
			TV.datum=$(this).attr('rel');
			$('#day_menu span').each(function(){ if($(this).attr('rel')==TV.datum) $(this).addClass('tv_dani3'); else $(this).removeClass('tv_dani3'); });
			TV.loadProgram();
		});
	},
	getCalendar: function(m,y){
		Core.putLoader( $('#inner_calendar') );
		$.get("/get_calendar.php",{ month: m, year: y }, function(data){ $('#inner_calendar').html(data); Core.initCalendar(); }  );
	},
	// stavlja loader na sredinu diva, ali ne vise od 200px
	putLoader: function(id) {
		var h=id.height();
		var w=id.width();
		var p=0,b=0;
		if(h>15) p=Math.round((h-15)/2);
		if(w>128) b=Math.round((w-128)/2);
		h=h-2*p;
		w=w-2*b;
		id.html('<div style="padding:'+(p>200?('200px '+b+'px '+(2*p-200)+'px '+b+'px'):(p+'px '+b+'px'))+';'+(h>15?('height:'+h+'px'):(''))+';width:'+w+'px;background-color:'+id.css("background-color")+'" id="ajaxLoader"><img alt="Loading..." src="/img/ajax-loader2.gif" width="128" height="15"/></div>');
	},
	// dodaje evenet za classu .id_hover iznad .id elemenata
	hover: function(id) {
		$('.'+id)
			.bind('mouseover',function( event ){ $(this).addClass(id+'_hover'); })
			.bind('mouseout',function( event ){ $(this).removeClass(id+'_hover'); });
	}


};

var TV = {
	kanalID:'1',
	paketID:'0',
	datum:'',
	saveTimeoutID:null,
	saved:true, // ako je saved false, trenutne pozicije se spremaju u privremenu varijablu kanalFav
	kanalFav:'',
	anim:0,
	alarmData:null, // svi alarmi
	editor:0,
	setTitle: function(t){
		$('#kanalNaziv').html(t);
	},
	setDateTitle: function(d){
		$('#kanalDatum').html(d);
	},
	loadProgram: function(){
		if($('#tv_program_body').length==0) return;
		TV.setChannelPos();
		Core.putLoader( $('#tv_program_body') );
		$('#kn_icon').css('background-position','0pt -'+((parseInt(TV.kanalID)-1)*16)+'px');
		$.get("/mode/mode.tv.program.php",{ kanalID: TV.kanalID, datum: TV.datum }, function(data){
			$('#tv_program_body').html(data);

			Core.initTvListing();
			TV.scrollProgram(0);
		}  );
	},
	/**
	 * Scrolla tv program
	 *  1 : scrolla na default poziciju
	 *  0 : automatski scrola da trenutna emisija bude vidljiva
	 * -1 : scrola do currently ili 50%
	 */
	scrollProgram: function(direction){
		if($.browser.msie==true){
			if($.browser.version<7) return;
		}
		var a=0;
		if(direction>0) {
			TV.scrollTv(0);
		}
		else if($('.currently').length>0) {
			a=$('.currently').prev().prev().offset().top-$('.tv_table').offset().top;
			if(direction==0 && $(window).scrollTop()+$(window).height()-$('.currently').offset().top > 0) {
				a=0;
			}
			else if(a>200) {
				TV.scrollTv(a);
			}
		} else if(direction==-1) {
			a=$('.tv_table tr').length/2*20;
			TV.scrollTv(a);
		}
		if(a!=0) {$('#prgup').height(0);$('#prgdown').height(18);} else {$('#prgup').height(18);$('#prgdown').height(0);}
	},
	scrollTv: function(a){
		var c=$('.tv_table_container');
		c.height($('.tv_table').height());
		$('.tv_table').animate({top:-a}, 400, function(){
			c.height(c.height()-a);
		});
	},
	loadTrenutno: function(datum,tColumns){
		TV.setChannelPos();
		Core.putLoader( $('#tab_trenutno') );
		$.get("/mode/mode.trenutno.php",{ datum: datum, t:tColumns }, function(data){  $('#srednji_stupac').html(data); Core.init(); }  );
	},

	setChannelPos: function(){
		if(TV.saved==true) return;
		var k='',kk=0;
		$('.phbox,.kn_mitems>div').each(function(){ k += $(this).attr('rel')+','; kk++; });
		clearTimeout( TV.saveTimeoutID );
		if(kk>100) {
			alert('Dozvoljeno je maksimalno 100 kanala!');
			return;
		}
		TV.kanalFav = k;
		TV.saveTimeoutID = setTimeout("TV.saveChannelPos();", 1000); // Save delay
		$('#saveMsg').css({color:'#999',opacity:1}).show().animate({opacity:7});
	},
	// snima kanale i zasivljuje svaki drugi kanal
	saveChannelPos: function(){
		TV.saved=true;
		$('#saveMsg').css({color:'#000'});
		$.post("/mode/mode.tv.kanali.php",{ myChannels:TV.kanalFav }, function(){
			Core.initChannelItems();
			$('#saveMsg').animate({opacity:0});
		} );
	},
	invertChannel: function(kID,t){
		 $.post('/mode/mode.tv.kanali.php',{myChannels:kID,invert:1},function(d){TV.kanalFav=d;});
		 if($(t).hasClass('star_full')) $(t).removeClass('star_full'); else $(t).addClass('star_full');
	},
	//postavlja aktivni paket, ako su vrijednosti null, cita se iz globalne varijable TV.paketID
	setPaket: function(paketID,paketName){
		TV.setChannelPos(); // u slucaju da su pozicije promjenjene ovo ce trigerirati snimanje
		if(paketID>=0 && paketName!=null) { $('#paket').html(paketName); }
		if(paketID>=0) { TV.paketID=paketID; TV.myKanal=0; } else TV.myKanal=1;
		Tools.close(false);
		Core.putLoader( $('#tv_kanali_body') );
		$.get("/mode/mode.tv.kanali.php", {
			pid : paketID
		}, function(data) {
			$('#tv_kanali_body').html(data);
			Core.initChannelMenu();
		});

	},

	/**
	 * Submita pretrazivanje
	 */
	search: function(frm){

		var scr=$('#searchChnList').val();
		$(frm).submit(
			function(d){
				$('#srednji_stupac').html(d);
				Core.initTvListing();
				$('.tv_table').highlight( $('#traziFrm2').find('input[name=q]').val() );
				if(scr) $('#searchChnList').val(scr);
			},
			Core.putLoader( $('#srednji_stupac') )
		);
		return false;
	},
	showSearchChannels: function(c){
		var L=$('#chn_list');
		if($(c).val()!='kanal') { L.css('display','none'); return; }
		L.css('display','block');
		if(L.html()!='') return;
		Core.putLoader( L );
		$.get("/mode/mode.search.php",{z:'chn_list'}, function(d){ L.html(d); });
	},
	/**
	 * Brzo pretrazivanje u alarmnu
	 */
	alarmSearch: function(kID,term){
		$('#arepeat').attr('checked','checked');
		$('#alertTo').hide();
		$('#alarmToKanal').show();
		$.post("/tool/alarm.php",{kanalID:kID,quickSearch:term}, function(d){ $('#alarmResult').html(d); });
	},

	alarmSubmit: function()
	{
		if($('#arepeat, #aonce').is(':checked')==false) {
			alert($('#SelectAlarmTip').val());
			return;
		}
		Core.submit('alarmform');
	},
	/**
	 * Renderira alarm box
	 */
	alarmBox: function()
	{
		$('#alarmHolder').html('');

		$.each(TV.alarmData, function(i,a){
			if(i>20) return false;
			var ts = new Date(a.ts*1000);
			var now = new Date();
			var m=ts.getMinutes(); if(m<10) m='0'+m;
			m+=' ';
			if(ts-now>60400000) m+= ts.getDate()+'.'+(ts.getMonth()+1)+'.';
			if(ts-now<600000 && ts-now>-(a.t*60000)) c=' class="alert"'; else c='';
			$('#alarmHolder').append(
				'<li><span class="kn_icon k'+a.kid+'"></span>&nbsp; '+
				'<b'+c+'>'+ts.getHours()+':'+m+
				'</b> '+ a.s.substring(0,50) +'</li>'
			);
          });
	},
	/**
	 * Povecava i smanjuje alarm box
	 */
	listAlarmBox: function()
	{
		$('#alarmHolder li').stop().show().css({opacity:1});
		var c = 30 * $('#alarmbox li').size();
		if($('#alarmHolder').css('height')!='30px') c=30;
		$('#alarmHolder').css('height',c);
	},
	/**
	 * Skriva alarmBox s fade efektom
	 */
	hideAlarmBox: function(z)
	{
		if(z==1) {
			$('#alarmHolder').stop().css({opacity:1});
		} else
		$('#alarmHolder').animate({'opacity':0.2},1000, function(){
			$(this).css({'height':30,opacity:1});
		});
	},
	/**
	 * Kruzi kroz zadnjih 6 alamarma s fade efektom
	 */
	circleAlarmBox: function(i)
	{
		if($('#alarmHolder').css('height')!='30px') {
			setTimeout('TV.circleAlarmBox(0)', 30000 );
			return;
		}
		var j=i;
		var s=$('#alarmbox li').size();
		if(s<=1) return;
		if(j==0) $('#alarmHolder li').show().css({opacity:1});

		$($('#alarmHolder li')[j]).animate({'opacity':0.1},800, function(){
			$(this).hide().css({opacity:1});
			j++;
			if(s<=j) {
				j=0; $($('#alarmHolder li')[0]).show().css({opacity:1});
			}
			setTimeout('TV.circleAlarmBox('+j+')', 30000 );
		});
	}

};

var Film = {

	join: function(pid)
	{
		// join the array
		var t='';
		$('.f'+pid+' input').each(function(a){ if(this.checked==true) if(t=='') t+=this.value; else t+='-'+this.value; });
		if(t=='') return '';
		else      return '&'+pid+'='+t;
	},
	filter: function()
	{
		var paket='';
		if($('#paketi').val()!=TV.paketID) paket = '&paketID='+$('#paketi').val();
		window.location = '?a=select'+Film.join('genres')+Film.join('years')+Film.join('ratings')+Film.join('packages')+paket;
	},
	clearFilter: function()
	{
		window.location = '/film/';
	}
};

var Cron = {
	ID:null,
	lastActivity:null,
	rnd:0, // unosi se slučajnost crona, tako da svi korisnici ne DDOS-aju u isto vrijeme :)
	init: function()
	{
		$( "body").live( "mousemove", function(){ Cron.lastActivity=new Date(); });
		Cron.rnd = Math.floor(Math.random()*4);
		Cron.ID = setInterval('Cron.cron()', 60*1000 ); // 1 min
		$('#chat_body').scrollTop(2000);


	},
	cron: function()
	{
		var d = new Date();
		var m = d.getMinutes();
		var fact=1;

		var cal_time=d.getHours()+':';
		if(m<10) cal_time+= '0'+m; else cal_time+= ''+m;
		$('#cal_time').html(cal_time);

		// korisnik nije aktivan više od sat vremena, povećavamo interval za 3x
		if(d-Cron.lastActivity>3600000)
		{
			fact=3;
		}
		// svakih 2 min
		if(m%(fact*1)==0) {
			Core.setCurrentShow();
		}

		// korinik nije aktivan 3h, nema vše refresha
		if(d-Cron.lastActivity>10800000)
		{
			return;
		}


		// svakih 5 min
		if(m%(fact*5+Cron.rnd)==0)
		{
			if( $('#autoRefresh').is(':checked') && TV.saved==true ) 	TV.loadTrenutno('',0);

			TV.alarmBox();

		}

		// svakih 10 min
		/*
		if(m%(fact*10+Cron.rnd)==0)
		{
			if($('#chat_txt').length>=0)
			if(!$('#chat_txt').is(':focus')) {
				chatSubmit();
				$('#chat_body').scrollTop(2000);
			}
		}
*/
	}
};


var Profile = {
	open: function(){
		Tools.loader();
		$.get("/tool/profile.php",{  }, function(data){ Tools.open(data,null); }  );
	},
	edit: function(){
		Tools.loader();
		$.get("/tool/profile.php",{ opt:'edit' }, function(data){
			Tools.open(data,null);
			$("#profileForm :input[type=text],#profileForm :input[type=password]").tooltip({
			    position: "center right",
			    offset: [-2, 10],
			    effect: "fade",
			    opacity: 0.8,
			    tip: '#regtip'
			});
		}  );
	},
	save: function(){
		if($('#currentPwd').val()=='') {
			alert($('#currentPwdTip').val());
			return;
		}
		Core.submit('profileForm');
	},
	saveSettings: function(){
		$('#settingsForm').submit(function(){Tools.close();TV.loadProgram();}, Tools.loader());
		 //Core.submit('settingsForm');
		 //Tools.close();
/**
 * TODO: za sve mode-ove
 */
		 //TV.loadProgram();
	}
};

function chatSubmit(){
	if(!$('chat_txt')) return;

	Core.putLoader( $('#chat_body') );
	$.post("/ax-chat-box.php",{ ax:1, chat_txt: $('#chat_txt').val()  }, function(data){ $('#chat_txt').val(''); $('#chat_body').html(data);  $('#chat_body').scrollTop(2000);  }  );
	return false;
}


function login(){
	Core.putLoader( $('#loginMsg') );
	$.post("/index.php",{ action:'login', luser:$('#luser').val(), pwd:$('#pwd').val(), zapamtime:$('#zapamtime').val() }, function(data){ $('#loginMsg').html(data); if(data=='OK') parent.location='/';  }  );

	return false;
}

function PBgen() {
	var css=$('.PBopt:checked').val();
	var src = 'http://tv.phazer.info/phazerbox/' + $('#PBgrupa').val() + '/&css=http://tv.phazer.info/css/v3/' + css;

	var tmp = '&lt;iframe&nbsp;src="' + src;
		tmp += '" allowtransparency="true" width="' + $('#PBwidth').val() + '"&nbsp;height="'  +$('#PBheight').val();
		tmp += '"&nbsp;frameborder="0"&nbsp;marginwidth="2"&nbsp; marginheight="2"&nbsp;scrolling="no"&gt;&lt;/iframe&gt;';
	$('#PBhtml').html(tmp);
	$('#PBexample').attr('src',src);
	$('#PBexample').css({width:$('#PBwidth').val()+'px',height:$('#PBheight').val()+'px'});
	$('#PBexampleDiv').css({width:$('#PBwidth').val()+'px',height:$('#PBheight').val()+'px'});
}


function tagtrazi(tag)
{
	$('#trazi_val').val(tag);
	TV.search('#traziFrm');
}

$(document).ready(function(){
 	Core.init();
 	Core.initTopMenu();
 	Core.initChannelMenu();
 	Core.initDayMenu();
 	Core.initTvListing();
 	TV.scrollProgram(0);
 	Core.initCalendar();
 	setTimeout('TV.circleAlarmBox(0)', 30000 );

 	Cron.init();

// 	$(window).bind('resize', function() {
// 		Core.resize('tools');
// 	});
// 	$(window).bind('scroll', function() {
// 		Core.resize('tools');
// 	});
 });