function MediaPlayer(){
    this.objName=null;
    this.currItem=null;
    this.height="290";
    this.width="410";
    this.displayheight="174";
    this.allowfullscreen="false";
    this.autostart="false";
    this.autoscroll="true";
	this.thiscurrentTime = null;
    this.loadFile=function(identify, content, id){
        var extention='';
        if(content=='music'){
            extention='sng';            
        }
        else if(content=='clip'){
            extention='clp';            
        }
        else if(content=='musicAlbum' || content=='musicalbum'){
            extention='abm';
        }
        this.identify=identify;
//        this.thisMovie(this.identify).loadXML(Gatex.getContextPath()+"/playlist/"+id+"."+extention);
        this.thisMovie(this.identify).loadFile({file:Gatex.getContextPath()+"/playlist/"+id+"."+extention});
//        setTimeout('mainRightPlayer.sendEvent("'+this.identify+'", "playitem", 0)', 1000);
    };
	this.current_pos=function(pos)
      {
		     thiscurrentTime = pos;
      };
    this.playPlayList=function(identify, url){
        this.identify=identify;
        this.thisMovie(this.identify).loadFile({file:url});
    };
	var creat_player=0;
	this.htmlAddItem=function(url){
        new Ajax.Request(url,
            {
                evalScripts:true,
                onFailure: function(){ alert(Lang.noResponse); },
                onSuccess:function(transport){
                    $('result').innerHTML=transport.responseText;
					if(creat_player==0){
						creat_player=1;
						mainRightPlayer.init('top_music_player', 'topFlv_player', '659', '247', '174', 0, 10);	
					}
					else
						mainRightPlayer.addItem('topFlv_player');
					
                }
            });
    };
    this.addItem=function(identify){
        var objName=this;
		var oldList = objName.thisMovie(identify).getPlaylist();
		var newItem = {title:$('playContentTitle').value,description:$('playContentGroup').value ,author:"BaA4ka",category:"BaA4ka" , image:Gatex.getStaticContextPath()+'pictures.php?n='+$('playContentImg').value+'&w=270&url=4', file:Gatex.getStreamsPath()+'songs/'+$('playContentFile').value, link:'http://music.dandaa.mn'};
		var newList = oldList.concat(newItem);
		//alert(thiscurrentTime);
		//currentStart =objName.thisMovie(identify).position;
		//alert(currentStart);
		currentpos = thiscurrentTime;
		objName.thisMovie(identify).sendEvent('LOAD', newList);
		
		setTimeout(objName.thisMovie(identify).sendEvent('SEEK', currentpos+1),0);
		setTimeout("player.sendEvent('PLAY', 'true')", 10000);
		//currentStart = ;
		
    };
    this.removeItem=function(cI){};
    this.getItemData=function(cI){};
    this.getData=function(){};
    this.getLength=function(){
        return this.thisMovie(this.identify).getLength();        
    };
    this.sendEvent=function(swf,typ,prm) {
      this.thisMovie(swf).sendEvent(typ,prm);
    };
    this.thisMovie=function(movieName){
	    if(navigator.appName.indexOf("Microsoft") != -1){
			return window[movieName];
		} else {
			return document[movieName];
		}
	};
}

function RightPlayer(){
    this.init=function(target, identify, width, height, displayheight, lan, size){
        this.target=target;
        this.identify=identify;
        this.width=width;
        this.height=height;
        this.displayheight=displayheight;
        this.lan=lan;
        this.size=size;
        this.build();
    };
    this.build=function(){
        this.autostart='true';
        this.repeat='true';
        this.shuffle='false';
		//alert($('playContentTitle').value);
		var addItems1 = {title:$('playContentTitle').value,description:$('playContentGroup').value ,author:"BaA4ka",category:"BaA4ka" , image:Gatex.getStaticContextPath()+'pictures.php?n='+$('playContentImg').value+'&w=270&url=4', file:Gatex.getStreamsPath()+'songs/'+$('playContentFile').value, link:'http://music.dandaa.mn'};
		
		var flashvars =
		  {
			'controlbar':           'bottom',
			'enablejs':				'true',
			'playlist':             'right',
			'playlistsize':         '271',
			'icons':                'true',
			'shuffle':     			'false',
			'repeat':     			'always',
			'frontcolor':           '373a37', // text & icons                  (green)
			'backcolor':            '54103a', // playlist background           (blue)
			'lightcolor':           '531039', // selected text/track highlight (red)
			'screencolor':          '000000', // screen background             (black)
			'skin':  				Gatex.getContextPath()+'/mediaplayer/stylish1.swf',
			'volume':  				'80',
			'autoscroll':           'true',		 
			'showdigits':           'true',	
			'smoothing':            'true',	
			'javascriptid':         this.identify,
			'autostart':            'true'
		  };
	
		  var params =
		  {
			'allowfullscreen':      'true',
			'allowscriptaccess':    'always',
			'bgcolor':              '#FFFFFF'
		  };
	
		  var attributes =
		  {
			'name':                 this.identify,
			'id':                   this.identify
		  };
	
		swfobject.embedSWF(Gatex.getContextPath()+"/mediaplayer/player.swf", this.target,this.width, this.height, '9', false, flashvars, params, attributes);
		
    };
    this.playAlbum=function(identify, url){
        this.identify=identify;
        var objName=this;
        new Ajax.Request(url,
            {
                evalScripts:true,
                onFailure: function(){ alert('Уучлаарай бидэнд энэ хүсэлт олдсонгүй') },
                onSuccess:function(transport){
                    $('result').innerHTML=transport.responseText;
                    var i=0;
                    while(i<$('playListSize').value){
                        objName.thisMovie(objName.identify).addItem({title:$('playContentTitle_'+i).value, image:Gatex.getStaticContextPath()+'/jscripts/mediaPlayer/preview.jpg', file:Gatex.getStreamsPath(), id:$('playContentPath_'+i).value, type: 'rtmp', link:'http://music.dandaa.mn'});
                        i++;
                    }
                }
            });
    };
    this.showSavePlayListWindow=function(){
        var objName=this;
        var top;
        if(window.pageYOffset){ top = window.pageYOffset; }
        else if(document.documentElement && document.documentElement.scrollTop){ top = document.documentElement.scrollTop; }
        else if(document.body){ top = document.body.scrollTop; }
        else{ top=0; }
        var element=$('savePlayListTarget');

        //element.style.left="0px";
        element.style.left=(parseInt(screen.width/2)-130)+"px";
        //element.style.top="0px";
        element.style.top=(top+parseInt(screen.height/2-300))+"px";
        element.style.display='';
        new Ajax.Request(Gatex.getContextPath()+'/static/jscripts/mediaPlayer/savePlayList.html',
            {
                evalScripts:true,
                onFailure: function(){ alert('Уучлаарай бидэнд энэ хүсэлт олдсонгүй') },
                onSuccess:function(transport){
                    element.innerHTML=transport.responseText;
                    $('savePlayListListTarget').innerHTML=objName.showPlayListData();
                    $('playListText').value=objName.getData();
                }
            });
    };
    this.hideSavePlayListWindow=function(){
        var element=$('savePlayListTarget');
        element.style.display='none';
    };
    this.showPlayListData=function(){
        var str = '';
        var i=0;
        while(i<this.getLength()){
            str +='<div class="savePlayListItem">';
            var obj = this.thisMovie(this.identify).itemData(i);
            for(var j in obj){
                if(j=='title'){
                    str +=obj[j];
                }
            }
            str +='</div>';
            i++;
        }
        return str;
    };
    this.getData=function(){
        var str = '';
        str += '<playlist version="1" xmlns="http://xspf.org/ns/0/">';
        str += '<trackList>';
        var i=0;
        while(i<this.getLength()){
            str += '<track>';
                var obj = this.thisMovie(this.identify).itemData(i);
                for(var j in obj){
                    if(j=='title'){
                        str += '<title>'+obj[j]+'</title>';
                    }
                    else if(j=='creator'){
                        str += '<creator>'+obj[j]+'</creator>';
                    }
                    else if(j=='image'){
                        str += '<image>'+obj[j]+'</image>';
                    }                    
                    else if(j=='file' && obj[j].indexOf('fileLibrary', 0)!=-1){
                        str += '<identifier>'+obj[j].substring(obj[j].indexOf("fileLibrary", 0), obj[j].length)+'</identifier>';
                    }
                    else if(j=='id'){
                        str += '<identifier>'+obj[j].substring(obj[j].indexOf("fileLibrary", 0), obj[j].length)+'</identifier>';
                    }
                }
                str += '<location>'+Gatex.getStreamsPath()+'</location>';
                str += '<meta rel="type">rtmp</meta>';
                str += '<info>http://music.dandaa.mn</info>';
            str += '</track>';
            i++;
        }
        str += '</trackList>';
        str += '</playlist>';
        return str;
    };
    this.savePlayList=function(){
        if(document.getElementById('playListName').value == '' || document.getElementById('playListName').value == null){
            window.alert("Та нэрээ оруулна уу?");
        } else {
            _handleRequest('post','savePlayListResult',Gatex.getContextPath()+'/core/content=playlist/object=playlist/action=addPlaylist/view=error', $('savePlayListForm').serialize(),true);
            mainRightPlayer.hideSavePlayListWindow();
            window.alert("Таны playlist амжилттай хадгалагдлаа. Хэсэг хугацааны дараа Playlist хэсгээс үзнэ үү.");
        }

    };
}

var player   =  null;
var seek     =     0;
var seekFlag = false;
var currentTime;

function timeMonitor(obj)
      {
		 // alert("timeMonitor");
        if((obj.position > 0) && (seekFlag))
        {
          seekFlag = false;
          player.sendEvent('SEEK', seek);
        }
		//alert(obj);
        currentTime = obj.position;
		mainRightPlayer.current_pos(currentTime);
      };
function seekSome(some)
      {
        seek = some;
		alert("seekSome");
        if(currentTime > 0)
        {
          player.sendEvent('SEEK', seek)
        }
        else
        {
          seekFlag = true;
          player.sendEvent('PLAY', 'true');
        }
      };
function playerReady(thePlayer) {
		
	player = window.document[thePlayer.id];
	player.addModelListener('TIME',  'timeMonitor');
	var newItem = {title:$('playContentTitle').value,description:$('playContentGroup').value ,author:"BaA4ka",category:"BaA4ka" , image:Gatex.getStaticContextPath()+'pictures.php?n='+$('playContentImg').value+'&w=270&url=4', file:Gatex.getStreamsPath()+'songs/'+$('playContentFile').value, link:'http://music.dandaa.mn'};
	setTimeout(player.sendEvent('LOAD', newItem), 100);
	
}


RightPlayer.prototype=new MediaPlayer();
var mainRightPlayer=new RightPlayer();
