var action={};

var m = MochiKit;

var cellsea = {

    action: null,
    length: 0, 
	flashPlayer: null,
		
	chandles: [
		'cRHandle',
		'cLHandle'
	],
		
	diff: function(lhs, rhs) {
            return new MochiKit.DOM.Coordinates(lhs.x - rhs.x, lhs.y - rhs.y);
    },
    
    tip: function(s){
       m.DOM.getElement('info').innerHTML=s;
       return true;
    },
    
    location: function(){ 
       
       offset=action.crop.cropPos.x-m.DOM.elementPosition('frequency').x;
       
       lt=(cellsea.length/action.crop.imgWidth*action.crop.cropSize.w).toFixed(0);
       begin=0;
       if(offset>0) begin=(cellsea.length/action.crop.imgWidth*offset).toFixed(0);
       end=Math.round(begin)+Math.round(lt);
     
       m.DOM.getElement('start').value=Math.round(begin);
       m.DOM.getElement('end').value=Math.round(end);
       m.DOM.getElement('duration').value=Math.round(lt);
     
       sec=begin%60;
       min=(begin-sec)/60;
       if(min<10) min='0'+min;
       if(sec<10) sec='0'+sec;
       
       esec=end%60;
       emin=(end-esec)/60;
       if(emin<10) emin='0'+emin;
       if(esec<10) esec='0'+esec;
       m.DOM.getElement('sstart').value=min+':'+sec;
       m.DOM.getElement('send').value=emin+':'+esec;
       m.DOM.getElement('sduration').value=lt;
    },
    
    error: function(s){
      if(typeof(s) == 'undefined')
        s="A runtime error has occurred.";
        alert(s);  
    },
    
    centerElement: function(elem) {
		var port = m.DOM.getViewportDimensions();		
		var elemSize = m.DOM.elementDimensions(elem);

		var center = new m.DOM.Coordinates(
			Math.round(port.w / 2 - elemSize.w / 2),
			Math.round(port.h / 2 - elemSize.h / 2));
		//console.log(center.x+"   "+center.y);
		m.DOM.setElementPosition(elem, center);
	},
	
    execute:function(){
	  
	   title=document.getElementById('title').value;
	   catselect=document.getElementById('category');
	   category=catselect.options[catselect.selectedIndex].value;

	   if(title==''||category==''){
	      alert("Please enter ringtone's title and category.");
	      return false;
	   }
	   document.getElementById("grayout").style.display="block";   
	   document.forms['rtmaker'].submit();
	},
	
	updateStatus:function(s){
	   document.getElementById("previewplayer").innerHTML=s;
	   document.getElementById("grayout").style.display="none";
	   document.getElementById("mask").style.display="block";
	   document.getElementById("preview").style.display="block";  
	},
	
	preview:function(f){
	  if(f.indexOf('mid')>0){
	  	document.getElementById("canvas").style.display="none";
		if(osName=='Windows'){
		 document.getElementById('previewplayer').innerHTML='<OBJECT CLASSID="CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95" CODEBASE="http://www.microsoft.com/ntserver/netshow/download/en/nsmp2inf.cab#Version=5,1,51,415"'+
		                                                ' type="application/x-oleobject" width=290 height=43>'+
														'<PARAM NAME="AutoStart" VALUE="1">'+
														'<PARAM NAME="FileName" VALUE="'+f+'">'+
														'<PARAM NAME="Loop" VALUE="1">'+
														'<PARAM NAME="ShowControls" VALUE="1">'+
														'<param name="ShowDisplay" value="0">'+
                                                        '<param name="ShowStatusBar" value="0">'+
														'<EMBED TYPE="video/x-ms-asf-plugin" PLUGINSPAGE="http://www.microsoft.com/windows/mediaplayer/download/default.asp"'+
														' SRC="'+f+'" ControlType="0" AutoStart="1" ShowControls="1" ShowStatusBar="0" Loop="1" width=290 height=43>'+
														'</OBJECT>';
		}else{
		 document.getElementById('previewplayer').innerHTML='<embed src="'+f+'" autostart="true" loop="true" width="290" height="35" />';
		}
	     
	  }else{
		var swfObj = new SWFObject("../flash/xspf_player_slim.swf", "player", "290", "20", "7", "#ffffff");
		swfObj.addParam("quality", "high");
		swfObj.addParam("swLiveConnect","true");
		swfObj.addParam("allowScriptAccess","always");
		swfObj.addVariable("autoplay",true);
		swfObj.addVariable("repeat_playlist",true);
		swfObj.addVariable("song_url", f);
		swfObj.addVariable("song_title", "Ringtone Preview");
		swfObj.write("previewplayer");
		cellsea.flashPlayer.SetVariable("stopS","");
	  }
	  document.getElementById("grayout").style.display="none";
	  document.getElementById("mask").style.display="block";
	  document.getElementById("preview").style.display="block"; 
	},
	
	closePreview:function(){
	   document.getElementById('previewplayer').innerHTML="";
	   document.getElementById("canvas").style.display="block";
	   document.getElementById("grayout").style.display="none";
	   document.getElementById("mask").style.display="none";
	   document.getElementById("preview").style.display="none";  
	},
	
	init: function() {
	     if(l <= 0){
	        window.setTimeout('cellsea.init()', 1000); 
	     }else{      
	        cellsea.length=l; 
	        var fadeins = new Slider(m.DOM.getElement("fadeinSlider"),m.DOM.getElement("fadeinI"));
	        var fadeouts = new Slider(m.DOM.getElement("fadeoutSlider"),m.DOM.getElement("fadeoutI"));
	        fadeins.setMinimum(0);
	        fadeins.setMaximum(5);
	        fadeouts.setMinimum(0);
	        fadeouts.setMaximum(5);
	        document.getElementById("fadeinSlider").style.display="block";
	        document.getElementById("fadeoutSlider").style.display="block";
	        fadeins.onchange = function () {
	           document.getElementById("sfadein").innerHTML = fadeins.getValue();
	           document.getElementById("fadein").value = fadeins.getValue();
            };
            fadeouts.onchange = function () {
	           document.getElementById("sfadeout").innerHTML = fadeouts.getValue();
	           document.getElementById("fadeout").value = fadeouts.getValue();
            };
	        
	        cellsea.flashPlayer=action.flash.getFlashObject("mp3crop");
	        action.crop.displayCrop();
		    cellsea.location();
		 }
	}//no ',' here for the IE
};  

action.flash = {

	getFlashObject: function(movieName){
	  if (window.document[movieName]) {
	      return window.document[movieName];
	  }
	  else if (navigator.appName.indexOf("Microsoft Internet")==-1){
	    if (document.embeds && document.embeds[movieName])
	      return document.embeds[movieName]; 
	  }
	  else
	    return document.getElementById(movieName);
	}	
};

action.crop = {

    cropPos: null,
    cropSize:null,
    offset:null,
    handle:null,
    bounds:null,
    imgWidth:498,
    imgHeight:125,
    
    down: function(e)
	{
		var self=action.crop; 
		e.stop();
		var p = e.mouse().page;
		var startPos = m.DOM.elementPosition('cropBox');
		self.offset=cellsea.diff(p,startPos);					
		m.Signal.connect('cropBox', 'onmousemove', self.drag);
		m.Signal.connect('cropBox', 'onmouseup', self.up);
	},
	
	drag: function(e)
	{
	    
		var self=action.crop; 
		e.stop();
		var p = e.mouse().page;
		var cropPos = cellsea.diff(p,self.offset);
		var startPos = m.DOM.elementPosition('frequency');

        imgSize=new m.DOM.Dimensions(self.imgWidth, self.imgHeight);
		
		if(cropPos.x<startPos.x) cropPos.x=startPos.x;
		if(cropPos.y<startPos.y) cropPos.y=startPos.y;
		if(cropPos.x+self.cropSize.w>startPos.x+imgSize.w) cropPos.x=startPos.x+imgSize.w-self.cropSize.w-2;
		if(cropPos.y+self.cropSize.h>startPos.y+imgSize.h) 
		  cropPos.y=startPos.y+imgSize.h-self.cropSize.h;
		m.DOM.setElementPosition('cropBox', cropPos);
		
		var h=m.DOM.elementPosition('frequency').y+self.imgHeight-m.DOM.elementPosition('canvas').y;
		var sliderSize = m.DOM.elementDimensions('cLHandle');	
		var sliderLPos=new m.DOM.Coordinates(cropPos.x-sliderSize.w/2,h);
		var sliderRPos=new m.DOM.Coordinates(cropPos.x-sliderSize.w/2+self.cropSize.w,h);	
		m.DOM.setElementPosition('cLHandle', sliderLPos);
		m.DOM.setElementPosition('cRHandle', sliderRPos);
		
		self.cropPos=cropPos;
		cellsea.location();
	},

	up: function(e){
	    e.stop();	
	    var self=action.crop;
	    m.Signal.disconnect('cropBox', 'onmousemove', self.drag);
		m.Signal.disconnect('cropBox', 'onmouseup', self.up);	
		offset=self.cropPos.x-m.DOM.elementPosition('frequency').x;
        begin=0;
        if(offset>0) begin=(cellsea.length/self.imgWidth*offset).toFixed(0); 
         if(cellsea.flashPlayer!=null){
           cellsea.flashPlayer.SetVariable("cue",begin);
         }	
	},
	
	
	controldown: function(e)
	{
		var self = action.crop;
		e.stop();
		
		self.handle = e.target().id;

		self.bounds = m.DOM.elementPosition('frequency');
		
		m.Signal.connect(document, 'onmousemove', self.controldrag);
		m.Signal.connect(document, 'onmouseup', self.controlup); 
	},
	

	controldrag: function(e)
	{
		var self = action.crop;
		e.stop();
		var sliderSize = m.DOM.elementDimensions('cLHandle');	
		var p = e.mouse().page;
		
		if(p.x < self.bounds.x) 
			p.x = self.bounds.x;
		
		//if(p.y < self.bounds.y+m.DOM.elementPosition('canvas').y) 
		//	p.y = self.bounds.y+m.DOM.elementPosition('canvas').y;
	
		if(p.x>self.bounds.x+496)
		  p.x=self.bounds.x+496;
		  
		//if(p.y>self.bounds.y+cellsea.image.size.h+m.DOM.elementPosition('canvas').y)
		  p.y=self.bounds.y;//+125+m.DOM.elementPosition('canvas').y;  
			
		lastSize = self.cropSize;
		newPos = self.cropPos;
		
		h=m.DOM.elementPosition('frequency').y+self.imgHeight-m.DOM.elementPosition('canvas').y;
		
		if (self.handle == 'cRHandle') {
		    w=p.x-self.cropPos.x;
		    if(w<10){ w=10; p.x=self.cropPos.x+10;}
            
            
			newSize = new m.DOM.Dimensions(w,self.imgHeight);
			
			var sliderRPos=new m.DOM.Coordinates(p.x-sliderSize.w/2,h);	
			m.DOM.setElementPosition('cRHandle', sliderRPos);
			
			lt=(cellsea.length/action.crop.imgWidth*newSize.w).toFixed(0);
	        if(cellsea.flashPlayer!=null){
	           cellsea.flashPlayer.SetVariable("length",lt);
	        }	
		} else if (self.handle == 'cLHandle') {
		    offsetx=p.x-self.cropPos.x;
		    
		    if(offsetx>0&&offsetx>lastSize.w){offsetx=lastSize.w-5;p.x=self.cropPos.x+lastSize.w-5;}
		    //if(offsety<0){offsety=5;p.y=self.cropPos.y+5;}
			newSize = new m.DOM.Dimensions(lastSize.w - p.x + self.cropPos.x,self.imgHeight);
				
			newPos = new m.DOM.Coordinates(p.x, self.cropPos.y);
			
			var sliderLPos=new m.DOM.Coordinates(p.x-sliderSize.w/2,h);	
			m.DOM.setElementPosition('cLHandle', sliderLPos);
			
			offset=newPos.x-m.DOM.elementPosition('frequency').x;
            lt=(cellsea.length/action.crop.imgWidth*action.crop.cropSize.w).toFixed(0);
            begin=0;
            if(offset>0) begin=(cellsea.length/action.crop.imgWidth*offset).toFixed(0);
            
	        if(cellsea.flashPlayer!=null){
	           cellsea.flashPlayer.SetVariable("length",lt);
	           cellsea.flashPlayer.SetVariable("cue",begin);
	        }
		}
		self.cropSize=newSize;
		self.cropPos=newPos;
		m.DOM.setElementPosition('cropBox', newPos);
		m.DOM.setElementDimensions('cropBox', newSize);
		cellsea.location();
	},
	
	controlup: function(e)
	{
		var self = action.crop;
		e.stop();
		m.Signal.disconnect(document, 'onmousemove', self.controldrag);
		m.Signal.disconnect(document, 'onmouseup', self.controlup);
	},
	
	enableCHandles: function() {
	    
	    m.Iter.forEach(cellsea.chandles,
			function(e) {
				m.Signal.connect(e, 'onmousedown', action.crop.controldown);
			}
	    );
	    m.Iter.forEach(cellsea.chandles,
			function(v) {
			  m.DOM.updateNodeAttributes(v, {'style': 'display:block'});
			}
	    );
	},
	
	disableCHandles: function() {
	
	    for(i=0;i<cellsea.chandles.length;i++){
		 m.Signal.disconnect(cellsea.chandles[i], 'onmousedown', action.crop.controldown);
		}
	    
	    m.Iter.forEach(cellsea.chandles,
			function(v) {
			  m.DOM.updateNodeAttributes(v, {'style': 'display:none'});
			}
	    );
	}, 
	
	displayCrop:function(e){
	
	    var self=action.crop;
		
		action.crop.enableCHandles();
        
        imgSize=new m.DOM.Dimensions(self.imgWidth, self.imgHeight);

		self.cropPos = new m.DOM.Coordinates(
			m.DOM.elementPosition('frequency').x+Math.round(imgSize.w * .1),
			m.DOM.elementPosition('frequency').y
		);
		
		displaySec=20;
		if(displaySec>cellsea.length) displaySec=cellsea.length;
		tempWidth=Math.round(imgSize.w*displaySec/cellsea.length);
		if(tempWidth>=imgSize.w * .9) tempWidth=imgSize.w * .8; 
		self.cropSize = new m.DOM.Dimensions(Math.round(tempWidth),Math.round(imgSize.h));
		
		m.DOM.updateNodeAttributes('cropBox', {'style': {
			'display': 'block'
		   }});
		
		m.DOM.setElementPosition('cropBox', self.cropPos);
		m.DOM.setElementDimensions('cropBox', self.cropSize);
	
		m.DOM.setElementClass('cropBox','cropTransparent');
		m.Signal.connect('cropBox', 'onmousedown', action.crop.down);
		
		var sliderSize = m.DOM.elementDimensions('cLHandle');	
		var sliderLPos=new m.DOM.Coordinates(m.DOM.elementPosition('frequency').x+Math.round(imgSize.w * .1)-sliderSize.w/2,
			m.DOM.elementPosition('frequency').y+self.imgHeight-m.DOM.elementPosition('canvas').y);
		var sliderRPos=new m.DOM.Coordinates(m.DOM.elementPosition('frequency').x+Math.round(imgSize.w * .1)-sliderSize.w/2+self.cropSize.w,
			m.DOM.elementPosition('frequency').y+self.imgHeight-m.DOM.elementPosition('canvas').y);	
		m.DOM.setElementPosition('cLHandle', sliderLPos);
		m.DOM.setElementPosition('cRHandle', sliderRPos);
		
		offset=action.crop.cropPos.x-m.DOM.elementPosition('frequency').x;
        lt=(cellsea.length/action.crop.imgWidth*action.crop.cropSize.w).toFixed(0);
        begin=0;
        if(offset>0) begin=(cellsea.length/action.crop.imgWidth*offset).toFixed(0);
        if(cellsea.flashPlayer!=null){
           cellsea.flashPlayer.SetVariable("length",lt);
           cellsea.flashPlayer.SetVariable("cue",begin);
        }
        m.DOM.getElement('createButton').style.display="block";
	},
	
	updateProgressBar: function(percent){
	    if(percent>0){
	      p=parseInt(percent*4.98);
	      m.DOM.getElement('progressBarBoxContent').style.width = p + 'px';
	    }
	}
};





