// JavaScript Document

function printBox(){

  try{urchinTracker('/print-box/');}catch(e){}

  var ajax = new Ajax( 'service/box.php?' + serialize( { 
    
    type: Box.type,
    height: Box.height,
    title: $('title_text').value
    
  }) );

  ajax.onComplete = function(a){
    
    Loading.setState(false);
    
    try{
      var data = eval( '(' + a + ')' );
    }catch(e){
      alert( 'Error: No data!' );
      return;
    }
    
    if( data.status == 'OK' ){
      
      DownFrame.setAdress( 'service/down.php?file=' + data.file );
    
    } else {
      alert( 'Error: ' + data.msg );
      try{urchinTracker('/print-box/error/' + data.msg);}catch(e){}
    }
    
  }
  
  ajax.onError = function(e){
    Loading.setState(false);
    alert( 'Error: ' + e.msg);
    try{urchinTracker('/print-box/com-error/' + e.msg);}catch(e){}
  }
  
  Loading.setState(true);
  ajax.send();
  
}


// ----------------------------------------------------------------------------


if( typeof XMLHttpRequest == "undefined" ){
	XMLHttpRequest = function(){
		return new ActiveXObject( navigator.userAgent.indexOf("MSIE 5") >= 0 ? "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP" );		
	};
}

function serialize(data){
		
		if(data == "") {
			return "";
		}
		
		var s = [];
		for(var item in data){
			s.push( item + "=" + encodeURIComponent( data[item] )); 
		}
		return s.join("&");
}

function Ajax( url, opt ){
  opt = opt || {};
  this.timeout = opt.timeout || 0;
  
  this.onError = opt.onError || function(err){};
  this.onComplete = opt.onComplete || function(data){};

  var xml = new XMLHttpRequest();
	xml.open( "GET", url, true );
  
  var that = this;
  xml.onreadystatechange = function(){

		if( xml.readyState != 4 ){ return; }
						
		if( xml.status == 200 ){
      that.onComplete( xml.responseText, xml );      
    } else {
      that.onError( { msg: 'Bed response status code (' + xml.status + ').'} ); 
    }

		xml = null;

	};

  this.send = function(){
    xml.send(null);
  }

}


var Loading = {
  
  state: false,
  
  init: function(){
    var button = $('print_button');
    var loader = $('loader');
    
    this.setState = function(state){
      if( state == this.state  ){ return; }
      
      if( this.state = state ){
        button.style.visibility = 'hidden';
        loader.style.display = 'block';
      } else {
        loader.style.display = 'none';
        button.style.visibility = 'visible';
      }
      
    }
  }
}

