////////////////////////////////////////////////////////////////////////////////////////////
// pixter player class // creatd by beliczki 2011
// available functions to call on flashVideo[0]
// 
// getDuration
// getCurrentTime 
// getPlaylistIndex
// stayTuned 
// playVideo
// pauseVideo
// 		
// getVersion
// setupDefaults
// setupDesign
// setupContent
// setupAnnotation
////////////////////////////////////////////////////////////////////////////////////////////
var pixterPlayer = function (d) {

	var gsm_gemius_identifier = 'zC6biPBy7IO3G3cLQaY7baR.P6KiMiMEagscyZDAjWX.r7';
	var gsm_gemius_hitcollector = 'http://shu.hit.gemius.pl';
	var gsm_gemius_playerId = "pixterPlayer." + d.displayType;
	var gsm_gemius_customPackage;

	var playlist;
	var relatedlist;
	var flashSrc;
	var flashState;
	var menuEnabled;
	var flashVideo;
	var header;
	var headerDOMstore;
	var title;
	var menu;
	var related;
	var annotation;
	var subtitler;
	var TXTsubtitles;
	var TXTsubtitleIndex;
	var posterImage;
	var videoTotalTime;
	var embedCode;
	var root = this;
	var metaData = new Object();
	this.defaults = d;
    var video_started_play = false;
    var banner_started_play = false;

	////////////////////////////////////////////////////////////////////////////////////////////////////	
	//flash object is ready for communication event handler
	this.onFlashReady = function () { 
		flashState = 'init';
		this.onTrace('playerVersion:'+flashVideo[0].getVersion());
		this.onTrace('flashState:'+flashState);
	//	flashVideo[0].setupDesign(this.defaults.color);
		flashVideo[0].setupDefaults(this.defaults);
		flashVideo[0].setupContent(playlist);
	}

	////////////////////////////////////////////////////////////////////////////////////////////////////	
	//video states - event handler - available types (playing  stopped pause loading buffering seeking)
	this.onStateChanged = function (ev) { 
		//data communication goes here ... eg:AJAX
		if (ev.type == 'playing' && video_started_play==false && playlist[this.defaults.playlistIndex].type=='feature') {
            video_started_play = true;
            video.updateNumclick(playlist[this.defaults.playlistIndex].videoID);                             
        }
		if (ev.type == 'playing' && banner_started_play==false && playlist[this.defaults.playlistIndex].type=='commercial') {
            banner_started_play = true;
            video.updateNumclick(playlist[this.defaults.playlistIndex].videoID);                             
        }		
		mp.attr('class',this.defaults.displayType+' '+ev.type);
		//gemius 
		if (ev.type == 'playing') {
			gemiusStream.event(	gsm_gemius_playerId, //playerId
													playlist[this.defaults.playlistIndex].videoAzon, //materialIdentifier
													flashVideo[0].getCurrentTime(), // timeIndex in seconds
													'playing'); // event type
		}
		if (ev.type == 'pause') {
			gemiusStream.event(	gsm_gemius_playerId, //playerId
													playlist[this.defaults.playlistIndex].videoAzon, //materialIdentifier
													flashVideo[0].getCurrentTime(), // timeIndex in seconds
													'paused'); // event type
		}
		
		//if you have anything to measure (like video is playing so user started to watch)
		//console.log show the states 
		flashState = ev.type;
		this.onTrace('flashState:'+ev.type);
	}
	////////////////////////////////////////////////////////////////////////////////////////////	
	//video is loading we received metadata - event handler
	this.onMetaData = function (name, value) { 
	
		//data communication goes here ... eg:AJAX
		
		//if you have anything to measure (like video is playing so user started to watch)
		metaData[name] = new Object();
		metaData[name] = value;
		if (name == 'duration'){ 
            videoTotalTime = value;
        }
		this.onTrace('Metadata:'+ name + ' = ' + value);
	}
	////////////////////////////////////////////////////////////////////////////////////////////	
	//screen has changed
	this.onScreenSizeChanged = function (sizeOptionName) { 
		if (!mp.hasClass('embedded')) {
			//this.defaults.timeIndex =  flashVideo[0].getCurrentTime();
			if (flashState == 'playing') this.defaults.autoPlay = true; else this.defaults.autoPlay = false;
			if (sizeOptionName == 'small') {
				$('#pixter-showroom').attr('class','');
				$('#pixter-content-showroom').attr('class','small on');
				flashVideo.remove();
				mp.detach().appendTo('#pixter-content-showroom');
				
			//	flashSrc = "pixter_player.swf?cache="+Math.random(100000);
				flashSrc = "http://static.pixter.hu/pixter_player.swf";
				flashembed("pixter_mediaplayer_flashHolder", {src: flashSrc, id:'pixter_mediaplayer_flashfallback', width:'100%', height:'100%', bgcolor:'#000000', wmode: 'opaque'}, {});
				flashVideo = $('#pixter_mediaplayer_flashfallback');
                $("#pixter-title .video-toolz, #pixter-title .video-toolz-brand").removeClass("on");
                $("#pixter-title .video-toolz, #pixter-title .video-toolz-brand").addClass("off");
                $("#pixter-content-left .video-toolz, #pixter-content-left .video-toolz-brand").removeClass("off");
                $("#pixter-content-left .video-toolz, #pixter-content-left .video-toolz-brand").addClass("on");
			}
			if (sizeOptionName == 'large') {
				$('#pixter-content-showroom').attr('class','');
				$('#pixter-showroom').attr('class','on');
				flashVideo.remove();
				mp.detach().appendTo('#pixter-showroom .viewScreen');
				
		//		flashSrc = "pixter_player.swf?cache="+Math.random(100000);
				flashSrc = "http://static.pixter.hu/pixter_player.swf";
				flashembed("pixter_mediaplayer_flashHolder", {src: flashSrc, id:'pixter_mediaplayer_flashfallback', width:'100%', height:'100%', bgcolor:'#000000', wmode: 'opaque'}, {});
				flashVideo = $('#pixter_mediaplayer_flashfallback');
                $("#pixter-content-left .video-toolz, #pixter-content-left .video-toolz-brand").removeClass("on");
                $("#pixter-content-left .video-toolz, #pixter-content-left .video-toolz-brand").addClass("off");
                $("#pixter-title .video-toolz, #pixter-title .video-toolz-brand").removeClass("off");
                $("#pixter-title .video-toolz, #pixter-title .video-toolz-brand").addClass("on");
			}
			this.defaults.screenSize = sizeOptionName;
		}
		this.onTrace('ScreenSize:'+ sizeOptionName);

	}
	////////////////////////////////////////////////////////////////////////////////////////////	
	//screen has changed
	this.onTimeIndexChanged = function (t) { 
		this.defaults.timeIndex =  t;
	}

	////////////////////////////////////////////////////////////////////////////////////////////	
	//video data is available and started to load
	this.onVideoInit = function (source,pi) {  //playListIndex
		this.defaults.playlistIndex = pi;
		
		
		//data communication goes here ... eg:AJAX
		
		
		//gemius gemiusStream.newStream
		gsm_gemius_customPackage = [
			{name:"NAME", value:playlist[pi].title},
			{name:"URL", value:source},
			{name:"HD", value:this.defaults.HD},
			{name:"PLAYER_SKIN", value:this.defaults.brand}
		];
        var treeids=new Array();
        if(playlist[pi].brandID !=0){
            treeids.push(playlist[pi].brandID);
        }
        if(playlist[pi].categoryID !=0){
            treeids.push(playlist[pi].categoryID);
        }
		gemiusStream.newStream(	gsm_gemius_playerId, //playerId
														playlist[pi].videoAzon,  // materialIdentifier
														playlist[pi].vTotalTime,  // totalTime
														gsm_gemius_customPackage,  // customPackage
														null,  // additionalPackage
														gsm_gemius_identifier,  // IDENTIFIER
														gsm_gemius_hitcollector,  // HITCOLLECTOR
														treeids);  // treeId
		//console.log(treeids);
		//set menu properties regarding video type commercial or else
		if ( playlist[pi].type == 'commercial' ) { headerDOMstore = header.detach(); } 
		else if (headerDOMstore){ mp.append(headerDOMstore); } 
		//if the video is feature movie we load content for related elemets
		if (  playlist[pi].type == 'feature' && !mp.hasClass('subtitleCreator') ) $.getJSON(this.defaults.relatedlistURL, this.onRelatedListLoaded);
		//annotation load
		var srtUrl = playlist[pi].srt+"?cache="+Math.random(100000);
		if(srtUrl != '') $('.srtString', annotation).load(srtUrl, function (responseText, textStatus, req) { root.onAnnotationLoaded(responseText) });
		if(this.defaults.TXT == 'on') this.onAnnotationVisibile(true);
		//visual elements  
		if (mp.hasClass('embedded')) {
			$('a', title).html(playlist[pi].title);
			$('a', title).attr('href',playlist[pi].permaLink);
		}
		flashVideo[0].setupDefaults(this.defaults);
		this.rearrange();
		this.onTrace('posterURL:'+ pi + ' : ' + playlist[pi].poster);
		this.onTrace('videoURL:'+ pi + ' : ' + source);
        if(playlist[pi].type=='feature'){
         //   video.updateNumclick(playlist[pi].videoID);
        }       
        
	}
	
	////////////////////////////////////////////////////////////////////////////////////////////	
	//getJson playlist success function
	this.onPlayListLoaded = function (data, status) { 
			playlist = data;
			//before jquery and JSON is loaded
			//mediaplayer and thus flash layer is not to be in display list
		//	var src = "pixter_player.swf?cache="+Math.random(100000);
			var src = "http://static.pixter.hu/pixter_player.swf";
			flashembed("pixter_mediaplayer_flashHolder", {src: src, id:'pixter_mediaplayer_flashfallback', width:'100%', height:'100%', bgcolor:'#000000', wmode: 'opaque'}, {});
			flashVideo = $('#pixter_mediaplayer_flashfallback');
	}
	////////////////////////////////////////////////////////////////////////////////////////////	
	//video completed playing event handler
	this.onPlayListEnded = function () { 
	
		//data communication goes here ... eg:AJAX

		//gemius
		gemiusStream.event(	gsm_gemius_playerId, //playerId
												playlist[this.defaults.playlistIndex].videoAzon, //materialIdentifier
												flashVideo[0].getCurrentTime(), // timeIndex in seconds
												'completed'); // event type
		//like video has been completed complete view stat increased
		mp.attr('class',this.defaults.displayType+' completed');
		header.addClass('visible');
        if(relatedlist.length>0){
            related.addClass('visible');
        }
		this.rearrange();
	}
	
	////////////////////////////////////////////////////////////////////////////////////////////	
	//getJson relatedlist success function
	this.onRelatedListLoaded = function (data, status) {
        if(data.length==0){
            $('.related', menu).addClass('hidden');            
        }
		relatedlist = data;
		var itemProto = $('.itemProto', related);
		for ( i in $('.itemStack .item', related) ) { $('.itemStack .item', related).remove(); }
		for ( i in data ) {
			var nd = itemProto.clone();
			nd.attr('class','item');
			$('.thumb img', nd).attr('src',data[i].thumb);
			$('.thumb img', nd).attr('alt',data[i].title);
			$('a', nd).attr('href',data[i].permaLink);
			$('.totalTime b', nd).html(data[i].videoTotalTime);
			nd.appendTo('.itemStack', related);
            flashVideo[0].addReletedItem(data[i]);
		}
		$('img', related).mouseover(function () {
			$('a', title).html('&raquo '+$(this).attr('alt'));
		});
		$('img', related).mouseout(function () {
			if (root.defaults.displayType == 'embedded') $('a', title).html(playlist[flashVideo[0].getPlaylistIndex()].title); 
			else $('a', title).html('&raquo');
		});
		$(".item", related).hover(
			function () {	$(this).css('background-color','rgb('+root.defaults.color.R+','+root.defaults.color.G+','+root.defaults.color.B+')');	},
			function () { $(this).css('background-color','white');}
		);
	}

	////////////////////////////////////////////////////////////////////////////////////////////	
	//mouse handler - bring mouse events out of flash to DOM
	this.onMouseActive = function (ma) { 

	} 
	////////////////////////////////////////////////////////////////////////////////////////////	
	//annotation handler
	this.onAnnotationVisibile = function (v) { 
		v? annotation.addClass('visible'):annotation.removeClass('visible');
		this.defaults.TXT = v?'on':'off';
	}
	this.onHDoption = function (v) { 
		this.defaults.HD = v?'on':'off';
		this.defaults.resolution = v?'flvHD':'flvLR';
	}

    this.onAnnotationLoaded = function (responseText) {
        parseSrt(responseText);
    	flashVideo[0].setupAnnotation(TXTsubtitles);
    	if (mp.hasClass('subtitleCreator')) {
    	  updateSubtitleBox();
        }        
    }

    function updateSubtitleBox(){
        var subhtml = '';
        for(var s in TXTsubtitles) {
			subhtml += TXTsubtitles[s].n+'&nbsp;&nbsp;<a href="#" class="edit-link" id="'+s+'">szerkeszt</a><br />';
			subhtml += toTime(TXTsubtitles[s].i) +' --> '+ toTime(TXTsubtitles[s].o)+'<br />';
			subhtml += TXTsubtitles[s].t +'<br /><br />';       
        }		  
        $("#subtitles").html(subhtml);  

        $('.edit-link').click(function (){ 
            var s = $(this).attr("id");
            var akt_index = parseInt(s.replace('s',''));
            var prev_max = 0;
            var next_min = 0;
            if(akt_index>1){
                var prev = akt_index-1;
                prev_max = TXTsubtitles['s'+prev].o;
            }
            var next = akt_index+1;
            if(TXTsubtitles['s'+next] != undefined){
                next_min = TXTsubtitles['s'+next].i;
            }
            $("#d-edit-from").val(toTime(TXTsubtitles[s].i));
            $("#d-edit-to").val(toTime(TXTsubtitles[s].o));
            $("#d-edit-text").html(TXTsubtitles[s].t);
            dialog.show("dialog-edit-sub",
    			 function(){
    			    var kezd = toSeconds($("#d-edit-from").val()); 
    			    var bef = toSeconds($("#d-edit-to").val());
                    var jo = true; 
                    if(isNaN(kezd)){
                        $("#subt_error").html('A kezdet hibás!')
                        jo = false; 
                    } 
                    if(isNaN(bef)){
                        $("#subt_error").html('A vége hibás!')
                        jo = false; 
                    }
                    if(jo){
                        if(bef<kezd){
                            $("#subt_error").html('A vége nagyobb a kezdetnél!')
                            jo = false;                             
                        }else if(kezd<prev_max){
                            $("#subt_error").html('A kezdet kisebb mint az előző felirat vége!')
                            jo = false;                                                         
                        }else if( next_min>0 && bef>next_min){
                            $("#subt_error").html('A vége nagyobb mint a következő felirat kezdete!')
                            jo = false;                                                         
                        }
                    }
                    
                    if(jo){
                        $("#subt_error").html('');
        				TXTsubtitles[s].t = $("#d-edit-text").val();
        				TXTsubtitles[s].i = toSeconds($("#d-edit-from").val());
        				TXTsubtitles[s].o = toSeconds($("#d-edit-to").val());
    
        				var srt_ = '';
        				var save_error = new Array();
        				var srt_index = 1;
        				for(s in TXTsubtitles) {
        						//console.log(s + ':'+TXTsubtitles[s].n + ' // ' + toTime(TXTsubtitles[s].i) + '--' + toTime(TXTsubtitles[s].i) + 'TXT:  ' + TXTsubtitles[s].t + '='+ TXTsubtitles[s].t.length )
        						if (TXTsubtitles[s].i == TXTsubtitles[s].o) save_error.push('noSubtitleTimeInterval');
        						if (TXTsubtitles[s].t.length == 0) save_error.push('noSubtitleLength');
        						if (TXTsubtitles[s].i != TXTsubtitles[s].o && TXTsubtitles[s].t.length > 0) {
        							srt_ += srt_index+'\n';
        							srt_ += toTime(TXTsubtitles[s].i) +' --> '+ toTime(TXTsubtitles[s].o)+'\n';
        							srt_ += TXTsubtitles[s].t +'\n\n';
        							srt_index ++;
        						}
        				}
        				for(e in save_error) {
        					$('.subtitlerMessage .'+save_error[e], subtitler).addClass('visible');
        				}
        
        				//alert(srt_);
        				parseSrt(srt_);
                        flashVideo[0].setupAnnotation(TXTsubtitles);    				
        				video.save_subtitle(srt_);
                        updateSubtitleBox();
                        $("#dialog-edit-sub").dialog("close");
                    }
                 },
    	         null,
                {h: 300, w: 400,okNoClose: true}
            )
        });              
    }

	
	function parseSrt(data){
		var srt = data;
    srt = srt.replace(/\r\n|\r|\n/g, '\n');
		TXTsubtitles = new Object();
    srt = strip(srt);
    var srt_ = srt.split('\n\n');
    for(s in srt_) {
        st = srt_[s].split('\n');
        if(st.length >=2) {
          n = parseInt(st[0]);
          i = strip(st[1].split(' --> ')[0]);
          o = strip(st[1].split(' --> ')[1]);
          t = st[2];
          if(st.length > 2) {
            for(j=3; j<st.length;j++)
              t += '\n'+st[j];
          }
          is = toSeconds(i);
          os = toSeconds(o);
          TXTsubtitles['s'+n] = {n:n, i:is, o:os, t:t};
        }
    }
  }
	
	function toTime (seconds) {
		var milSec = (Math.round(    (seconds - Math.floor(seconds))*1000   )  /1000).toString().split('.')[1];
//		var clock = (Math.floor(seconds / 3600) < 10 ? '0' : '') + Math.floor(seconds / 3600).toString() + ':' + (Math.floor(seconds / 60) < 10 ? '0' : '') + Math.floor(seconds / 60).toString() + ':' + (seconds % 60 < 10 ? '0' : '') + (Math.floor(seconds % 60)).toString();
		var clock = (Math.floor(seconds / 60) < 10 ? '0' : '') + Math.floor(seconds / 60).toString() + ':' + (seconds % 60 < 10 ? '0' : '') + (Math.floor(seconds % 60)).toString();
		if(milSec==undefined) milSec=0;
        return clock+','+milSec;
	}
	
	function toSeconds(t) {
		var s = 0.0;
		if(t) {
			var p = t.split(':');
			for(i=0;i<p.length;i++) {
				s += Math.pow(60,p.length-i-1) * p[i].replace(',', '.');
			}
		}
		return s;
	}
	function strip(s) {
        return s.replace(/^\s+|\s+$/g,"");
	}
	function nl2br(s) {
		return s.replace(/\r\n|\r|\n/g,'<br/>');
	}
	
  this.onAnnotationChanged = function (ev) {

		$('.actualLine', annotation).attr('class', 'actualLine '+(ev.exist?'visible':'hidden'));
		if (ev.id != 0) $('.actualLine', annotation).html( nl2br(TXTsubtitles[ev.id].t) );
		if (mp.hasClass('subtitleCreator')) {
			if ( ev.exist == 1 && ev.id!=0) {
				TXTsubtitleIndex = ev.id;
				$('.actualLine', subtitler).val( TXTsubtitles[ev.id].t  );
				$('.iTime', subtitler).val( toTime(TXTsubtitles[ev.id].i) );
				$('.oTime', subtitler).val( toTime(TXTsubtitles[ev.id].o)  );
				$('.ctrlmod', subtitler).addClass('visible');
				$('.ctrladd', subtitler).removeClass('visible');
				
			} else {
				$('.actualLine', subtitler).val( "" );
				$('.iTime', subtitler).val( "" );
				$('.oTime', subtitler).val( "" );
				$('.ctrladd', subtitler).addClass('visible');
				$('.ctrlmod', subtitler).removeClass('visible');
			}
		}
	}
	
	////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////	
	//subtitle editor
	////////////////////////////////////////////////////////////////////////////////////////////
	$('.actualLine', subtitler).val('');
	$('.iTime', subtitler).val('');
	$('.oTime', subtitler).val('');

	//on edit start
	$('#edit', subtitler).click(function (){
			var mode;
	       $('.save').show();
	       $('.stepping').show();          
			$('.actualLine', subtitler).attr('readonly','');
			if ( $('.ctrladd', subtitler).hasClass('visible') ) mode = 'add';
			if ( $('.ctrlmod', subtitler).hasClass('visible') ) mode = 'mod';
			$('.ctrl'+mode+' .save', subtitler).addClass('visible');
			//$('.iTime', subtitler).attr('readonly','');
			//$('.oTime', subtitler).attr('readonly','');

			if ( !$('.iTimeHolder', subtitler).hasClass('selected') && !$('.oTimeHolder', subtitler).hasClass('selected')) 	{
				$('.oTimeHolder', subtitler).addClass('selected');
				$('.oTime', subtitler).css('background-color','rgb('+root.defaults.color.R+','+root.defaults.color.G+','+root.defaults.color.B+')');
			}
			
			//handling text change
			$('.actualLine', subtitler).keyup(function(){ 
				TXTsubtitles[TXTsubtitleIndex].t = $('.actualLine', subtitler).val();
				$('.actualLine',annotation).html( nl2br(TXTsubtitles[TXTsubtitleIndex].t) );
			});

			//handling time increment decrement
			$('.stepping a').click(function(){
                var kezd = toSeconds($('.iTime').val());
				var amount = 0;
				var direction = 0;
				var t = 0;
				var rs = '';
				var currentTime = toSeconds($(this).parent().parent().siblings('input').val());
				if ($(this).hasClass('plus')) direction = 1;
				if ($(this).hasClass('minus')) direction = -1;
				if ($(this).hasClass('sec')) amount = 1;
				if ($(this).hasClass('milsec')) amount = 0.1;
				t = currentTime + (direction*amount);
				if (t<0 || t<kezd) return;
				$(this).parent().parent().siblings('input').val(toTime(t));
				if ($(this).parent().parent().siblings('.iTime').val()) rs = 'i';
				if ($(this).parent().parent().siblings('.oTime').val()) rs = 'o';
				flashVideo[0].redrawAnnotation(rs,t);
			});
			
			//handling out time change
			if($('.oTimeHolder', subtitler).hasClass('selected')) {
				flashVideo[0].startRedrawAnnotation("o");
				//$('.oTime', subtitler).bind('change',outTimeRetyped);
			}
			$('.oTime', subtitler).click(function(){ 
				$(this).parent().addClass('selected');
				$(this).css('background-color','rgb('+root.defaults.color.R+','+root.defaults.color.G+','+root.defaults.color.B+')');
				$('.iTimeHolder', subtitler).removeClass('selected');
				$('.iTime', subtitler).css('background-color','white');
				flashVideo[0].startRedrawAnnotation("o");
			});
			//handling in time change
			if($('.iTimeHolder', subtitler).hasClass('selected')) {
				flashVideo[0].startRedrawAnnotation("i");
			}
			$('.iTime', subtitler).click(function(){ 
				$(this).parent().addClass('selected');
				$(this).css('background-color','rgb('+root.defaults.color.R+','+root.defaults.color.G+','+root.defaults.color.B+')');
				$('.oTimeHolder', subtitler).removeClass('selected');
				$('.oTime', subtitler).css('background-color','white');
				flashVideo[0].startRedrawAnnotation("i");
			});
			//finish and save 
			$('.save', subtitler).click(function(){ 
			
				flashVideo[0].stopRedrawAnnotation(); 
				
				$('.actualLine', subtitler).attr('readonly','readonly');
				$('.actualLine', subtitler).unbind('keyup');
				$('.ctrl'+mode+' .save', subtitler).removeClass('visible');
				$('.iTime', subtitler).unbind('click');
				$('.oTime', subtitler).unbind('click');
				$('.save', subtitler).unbind('click');
			
				var srt_ = '';
				var save_error = new Array();
				var srt_index = 1;
				for(s in TXTsubtitles) {
						//console.log(s + ':'+TXTsubtitles[s].n + ' // ' + toTime(TXTsubtitles[s].i) + '--' + toTime(TXTsubtitles[s].i) + 'TXT:  ' + TXTsubtitles[s].t + '='+ TXTsubtitles[s].t.length )
						if (TXTsubtitles[s].i == TXTsubtitles[s].o) save_error.push('noSubtitleTimeInterval');
						if (TXTsubtitles[s].t.length == 0) save_error.push('noSubtitleLength');
						if (TXTsubtitles[s].i != TXTsubtitles[s].o && TXTsubtitles[s].t.length > 0) {
							srt_ += srt_index+'\n';
							srt_ += toTime(TXTsubtitles[s].i) +' --> '+ toTime(TXTsubtitles[s].o)+'\n';
							srt_ += TXTsubtitles[s].t +'\n\n';
							srt_index ++;
						}
				}
				for(e in save_error) {
					$('.subtitlerMessage .'+save_error[e], subtitler).addClass('visible');
				}

				//alert(srt_);
				parseSrt(srt_);
				
				//AJAX data communication comes here
				//save "srt_" subtitle string to server
				video.save_subtitle(srt_);
                updateSubtitleBox();
				$('.save').hide();											
	           $('.stepping').hide();
               $('.stepping a').unbind('click');
			});
	});
	$('.remove', subtitler).click(function (){
		var updatedTXTsubtitles = new Object();
		var sx = 1;
        var _srt='';
        for(var s in TXTsubtitles) {
            if(s != TXTsubtitleIndex) {
    					updatedTXTsubtitles[s] = new Object();
    					updatedTXTsubtitles[s] = TXTsubtitles[s];
    					updatedTXTsubtitles[s].n = sx++;
    				srt_ += updatedTXTsubtitles[s].n+'\n';
    				srt_ += toTime(updatedTXTsubtitles[s].i) +' --> '+ toTime(updatedTXTsubtitles[s].o)+'\n';
    				srt_ += updatedTXTsubtitles[s].t +'\n\n';
    
            }
        }
		TXTsubtitles = updatedTXTsubtitles;
		flashVideo[0].setupAnnotation(TXTsubtitles);
		video.save_subtitle(srt_);
	});

	$('#add', subtitler).click(function (){
	   $('.save').show();

		var updatedTXTsubtitles = new Object();
		var insertDone = false;
		var sx = 1;
    for(var s in TXTsubtitles) {
        if(TXTsubtitles[s].o < flashVideo[0].getCurrentTime()) {
					updatedTXTsubtitles[s] = new Object();
					updatedTXTsubtitles[s] = TXTsubtitles[s];
					updatedTXTsubtitles[s].n = sx++;
        } else if (TXTsubtitles[s].i > flashVideo[0].getCurrentTime()) 
				{
					if (!insertDone) 
					{
						updatedTXTsubtitles['s'+sx] = new Object();
						updatedTXTsubtitles['s'+sx].i = flashVideo[0].getCurrentTime();
						updatedTXTsubtitles['s'+sx].o = flashVideo[0].getCurrentTime();
						updatedTXTsubtitles['s'+sx].t = "";
						updatedTXTsubtitles['s'+sx].n = sx++;
						insertDone = true;
					}
					updatedTXTsubtitles['s'+sx] = new Object();
					updatedTXTsubtitles['s'+sx] = TXTsubtitles[s];
					updatedTXTsubtitles['s'+sx].n = sx++;
				}
    }
		if (!insertDone) 
		{
			updatedTXTsubtitles['s'+sx] = new Object();
			updatedTXTsubtitles['s'+sx].i = flashVideo[0].getCurrentTime();
			updatedTXTsubtitles['s'+sx].o = flashVideo[0].getCurrentTime();
			updatedTXTsubtitles['s'+sx].t = "";
			updatedTXTsubtitles['s'+sx].n = sx++;
			insertDone = true;
		}
		TXTsubtitles = updatedTXTsubtitles;
    /*for(s in TXTsubtitles) {
			console.log(s+"//"+TXTsubtitles[s].n +": "+TXTsubtitles[s].t);
    }*/
		flashVideo[0].setupAnnotation(TXTsubtitles);
		$('#edit', subtitler).click();
	});
	
	
	//display new time
	this.onAnnotationItemUpdated = function (t,p) { 
		$('.selected input', subtitler).val(toTime(t));
		TXTsubtitles[TXTsubtitleIndex][p] = t;
		//alert ('00:'+TXTsubtitles[TXTsubtitleIndex][p]+',000')
	}
	
	

	////////////////////////////////////////////////////////////////////////////////////////////	
	//put stuff on console
	this.onTrace = function (e) { 
		try { if (this.defaults.debugMode) console.log(e); } catch(err) { 	/*console not available*/ }
	}

	////////////////////////////////////////////////////////////////////////////////////////////	
	//like communication
	$('#pixter_mediaplayer .like').click(function (){
		//console.log(menu);
		//data communication goes here eg:AJAX ... and then show message

    	$.get("/ajaxhelper.php", {type: 'video_like', id: playlist[flashVideo[0].getPlaylistIndex()].videoID, num: '1'},
    		function(data){
    		  $('#pixter_mediaplayer .message h2').html('Tetszett');
				if(data.error == 'auth_error'){
					$('#pixter_mediaplayer .message p').html('Ha tetszett a videó, <a href="http://www.pixter.hu/belepes" target="_blank">lépj be</a> a Pixteren, és értékeld!');
				}else if(data.error == 'already_like'){
				    $('#pixter_mediaplayer .message p').html('Már értékelted a videót!');		
				}else if(data.error == 'already_dislike'){
					return 'already_dislike';
				}else{
				    $('#pixter_mediaplayer .message p').html('Köszönjük, hogy értékelted a videót!');
				}
		      $('#pixter_mediaplayer .message').addClass('visible');
    		}
    	,'json');

	});
	
	////////////////////////////////////////////////////////////////////////////////////////////	
	//embed communication
	$('.embed', menu).click(function () {
		
		//data communication goes here eg:AJAX ... and then show message + embed code
		embedCode = '<iframe title="Pixter Videó lejátszó" width="590" height="330" src="http://static.pixter.hu/embed?id='+playlist[flashVideo[0].getPlaylistIndex()].videoID+'" frameborder="0" allowfullscreen></iframe>';
		
		$('#pixter_mediaplayer .message h2').html('Beágyazás');
		$('#pixter_mediaplayer .message p').html('<textarea style="height:80px;">'+embedCode+'</textarea><br/>Másold ki ezt a kódot és beillesztheted szinte bárhová.');
		$('#pixter_mediaplayer .message').addClass('visible');
		$('#pixter_mediaplayer .message textarea').click(function() {
		  $('#pixter_mediaplayer .message textarea').select();
		});
        $('#pixter_mediaplayer .message textarea').select();
		
	});

	////////////////////////////////////////////////////////////////////////////////////////////	
	//share communication
	$('#pixter_mediaplayer .share').click(function () {
        $('#pixter_mediaplayer .message h2').html('Megosztás');
        $("#share-kont").show();
        var sh_t = '<span style="float:left;"><input type="text" id="copytext" style="width:220px;" value="http://www.pixter.hu/video?id='+playlist[flashVideo[0].getPlaylistIndex()].videoID+'" /></span><span><a href="#" id="copybutton" style="margin-left: 10px;float: left; background:url(../images/button_copy.png) no-repeat; width: 70px; height: 24px;display:block;color: #636566;padding:3px 0 0 12px;text-decoration:none;">Másolás</a></span><br /><span title="Tovább küldöm" style="float:left;width: 130px;margin-top: 10px;"><img border="0" align="left" alt="Tovább küldöm" src="/images/mail.png" style="margin-right:10px;"><a title="Tovább küldöm" href="/video_tovabbkuld?id='+playlist[flashVideo[0].getPlaylistIndex()].videoID+'" target="_blank">Tovább küldöm</a></span><span title="Facebook" style="float:left;width: 100px;margin-top: 10px;"><img border="0" align="left" alt="Facebook" src="http://static.pixter.hu/img/icon_facebook.gif" style="margin-right:10px;"> <a target="_blank" onclick="return fbs_click()" href="http://www.facebook.com/share.php?u=http://www.pixter.hu/video?id='+playlist[flashVideo[0].getPlaylistIndex()].videoID+'" title="Facebook">Facebook</a></span><span style="float:left;width: 110px; margin-top: 8px;"><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fpixter.hu%2Fvideo%3Fid%3D'+playlist[flashVideo[0].getPlaylistIndex()].videoID+'&amp;layout=button_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;colorscheme=light&amp;height=20" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:23px;" allowTransparency="true"></iframe></span>';
		$('#pixter_mediaplayer .message p').html(sh_t)
        $('#pixter_mediaplayer .message').addClass('visible');
        $('a#copybutton').zclip({
        path:'js/ZeroClipboard.swf',
        copy:function(){return $('input#copytext').val();}
        });
        $('.zclip').css('top',$('#copybutton').position().top);        
        $('.zclip').css('left',$('#copybutton').position().left);        
	});
	
	////////////////////////////////////////////////////////////////////////////////////////////	
	//related manager + basic carousel
	var isTargetX = 0;
	$('.related', menu).click(function () {
		related.toggleClass('visible');
		if (related.hasClass('visible')){
			$('a', title).html('&raquo&nbsp');
		} else {
			if( mp.hasClass('embedded') ) $('a', title).html(playlist[flashVideo[0].getPlaylistIndex()].title);
			else $('a', title).html('');
		}
		root.rearrange();
	});
	//basic carussel left arrow action
	$('.left', related).click(function () { 
		var is = $('.itemStack', related);
		var iw = $('.item', related).width()+8;
		var position = is.position();
		if (isTargetX < iw ) { //
			isTargetX += iw;
			is.animate( { left: isTargetX }, 300, function() { /* Animation complete.*/});
		}
	});
	//basic carussel right arrow action
	$('.right', related).click(function () {
		var is = $('.itemStack', related);
		var allItems = $('.item', related);
		var iw = $('.item', related).width()+8;
		var position = is.position();

		if (isTargetX > -iw * (allItems.length+1) + related.width()  ) { //
			isTargetX -= iw;
			is.animate( { left: isTargetX }, 300, function() { /* Animation complete.*/});
		}
	});
	
	// fast multiple clicking of arrow buttons makes ugly selection 
	// this helps to remove the unwanted effect
	function disableSelection(element) {
			if (typeof element.onselectstart != 'undefined') {
					element.onselectstart = function() { return false; };
			} else {
					element.onmousedown = function() { return false; };
			}
	}
	//for ( var i in $('#pixter_mediaplayer .header'))  disableSelection($('#pixter_mediaplayer_related div').get(i));
	disableSelection($('#pixter_mediaplayer .header')[0]);

	////////////////////////////////////////////////////////////////////////////////////////////	
	//rearrange stuff	
	this.rearrange = function () {
		//title design
		menu.width(50*$('li.visible',menu).length+10);
		var fontSize = (mp.width()/25);
		if (fontSize < 12) fontSize = 12;
		if (fontSize > 26) fontSize = 26;
		$('a',title).css('font-size',fontSize+'px');
		$('h2',message).css('font-size',fontSize+'px');

        var annotationFontSize = (mp.width()/25);
        if (annotationFontSize < 6) annotationFontSize = 6;
        if (annotationFontSize > 16) annotationFontSize = 16;
        $('.actualLine', annotation).css('font-size',annotationFontSize+'px');
        $('.actualLine', annotation).css('line-height',(annotationFontSize*2-2)+'px');
        if (mp.width()<320) annotation.css('bottom','36px'); else annotation.css('bottom','50px');

		//menu adjust
		if (mp.hasClass('embedded')) {
			var b = new Boolean();
			b = (mp.width()<=380);
			$('.share', menu).removeClass(b?'visible':'hidden').addClass(b?'hidden':'visible'); 
			b = (mp.width()<=320);
			$('.like', menu).removeClass(b?'visible':'hidden').addClass(b?'hidden':'visible'); 
			b = (mp.width()<=280)
			menu.removeClass(b?'enabled':'disabled').addClass(b?'disabled':'enabled'); 
		}
		//carusel adjust
		$('.itemStack', related).width( ($('.item', related).length+1)*$('.item', related).width());
		$('.carousel', related).css('width',mp.width()-84+'px'); 
		return true;
	}
	
	////////////////////////////////////////////////////////////////////////////////////////////	
	//whole thing starts here
	this.init = function () {
		
		//loadplaylist
		$.getJSON(this.defaults.playlistURL, this.onPlayListLoaded);

		//object shortcuts
		mp = $('#pixter_mediaplayer');
		header = $('#pixter_mediaplayer .header');
		title = $('#pixter_mediaplayer .title');
		menu = $('#pixter_mediaplayer .menu');
		related = $('#pixter_mediaplayer .relItems');
		annotation = $('#pixter_mediaplayer .annotation');
		message = $('#pixter_mediaplayer .message');
		subtitler = $('#pixter_video_subtitler');
		
		//displayType & displaySize
		mp.addClass(this.defaults.displayType);
		//mp.addClass(this.defaults.screenSize);
		if(mp.hasClass('embedded')) {	header.addClass('visible');	}
		if(!mp.hasClass('embedded')) {	$('.share', menu).addClass('hidden');	}
		if(!mp.hasClass('embedded')) {	$('.embed', menu).addClass('hidden');	}
		if(!mp.hasClass('embedded')) {	$('.like', menu).addClass('hidden');	}
		if(mp.hasClass('subtitleCreator')) {	header.remove();}
		header.mouseenter(function(){	header.addClass('visible');  });
		header.mouseleave(function(){	
			header.removeClass('visible'); 
			related.removeClass('visible'); 
			if( mp.hasClass('embedded') ) $('a', title).html(playlist[flashVideo[0].getPlaylistIndex()].title);
			else $('a', title).html('');
		});
		
		subtitler.mouseenter(function(){	flashVideo[0].stayTuned(1); });
	
		//html play button
		$('.play', mp).click(function (){ flashVideo[0].playVideo(); });
		$('.replay', mp).click(function (){ 
			flashVideo[0].playVideo(); 
		});
		$('a', title).css('opacity',0.5);
		$('a', title).css('color','#ffffff');
		$('a', title).css('textShadow','#000000 2px -2px 5px');
		$('a', title).mouseover( function (){
			$(this).css('color','rgb('+root.defaults.color.R+','+root.defaults.color.G+','+root.defaults.color.B+')');
			$(this).css('opacity',1);
		});
		$('a', title).mouseout( function (){
			$(this).css('color','#ffffff');
			$(this).css('opacity',0.5);
		});
		
		//menu design
		$('.color', menu).css('background-color','rgb('+root.defaults.color.R+','+root.defaults.color.G+','+root.defaults.color.B+')');
		if (mp.width()<320) menu.addClass('small');
		//related design
		$('.color', related).css('background-color','rgb('+root.defaults.color.R+','+root.defaults.color.G+','+root.defaults.color.B+')');
		
		//brnading design
		$('#pixter_mediaplayer .branding').addClass(this.defaults.brand);
		$('#pixter_mediaplayer .branding a').attr('href',this.defaults.brandURL);
		
		//window layer design
		$('#pixter_mediaplayer .message h2').css('color','rgb('+root.defaults.color.R+','+root.defaults.color.G+','+root.defaults.color.B+')');
		$('#pixter_mediaplayer .message .cover').css('opacity','0.4');
		$('#pixter_mediaplayer .message .cover').click(function (){	$('#pixter_mediaplayer .message').removeClass('visible');	});
		$('#pixter_mediaplayer .message .close').click(function (){	$('#pixter_mediaplayer .message').removeClass('visible');	});
		
		this.rearrange();
	}
	//resize bind
	$(window).resize(this.rearrange);
	
	//self execute
	this.init();

}

