﻿var G_wait_thread_time = 20; // in sec
var G_wait_alert_offline_time = 45; // in sec

var cPage = newClass(null, {

    onLoad : function ()
    {
        var div = document.getElementsByTagName("div");
        for(var i=0; i < div.length; i++)
        {
            if (div[i].className.indexOf("skinbutton") > -1){
                this.addHandler($(div[i].id), "mouseover", this.__skinButtonOver);
                this.addHandler($(div[i].id), "mouseout", this.__skinButtonOut);
            }   
        }
        this.__onSessionThread({code: 0});
    },
    
    __processSessionThread: function ()
    {
		if(typeof window.G_order_id == 'undefined') window.G_order_id = 0;
        this.jsonRequest('SessionThread', {'active_order_id': window.G_order_id}, true, 'service');
    },
    
    __onSessionThread: function(data)
    {
		switch (data.code)
        {
			// no errors
            case 0:
            case 'normal':
				if (page._lock_alert)
				{
					page._lock_alert.style.display = 'none';
					page._lock_alert = null
					page.unFade(true);
				}
				else if (page._lock_timer)
				{
					clearTimeout(page._lock_timer)
					page._lock_timer = null;
				}
            break;
            case 'logout':
				if (window.G_settings)
				{
					alert('WARNING: Yor session has been closed. Page will be reloaded.');
					location.reload();
				}
				return;
            break;			
			// ERR #1: Session destroyed by server: User with 
            case 'logged_another':
		        page.fade();
				$('sessionDestroyedRelogin').style.display = 'block';
				page.setToCenter($('sessionDestroyedRelogin'));
				return;
            break;
			// ERR #2: Action order changed.
            case 'chanched_active_order':
				alert('WARNING: Active order has been changed. Page will be reloaded.');
				location.reload();
				return;
            break;			
			default:
				if (!page._lock_timer)
				{
					page._lock_timer = setTimeout(function()
					{
						page.fade();
						var sna = $('serverNotAvalible');
						if (sna)
						{
							sna.style.display = 'block';
							page.setToCenter(sna);
							page._lock_alert = sna;
						}
						page._lock_timer = null;
					}, G_wait_alert_offline_time * 1000);
				}
            break;	
        }
		var x = setTimeout(function()
		{
			page.__processSessionThread();
		}, G_wait_thread_time * 1000); // 10 sec
	},
    
    __skinButtonOver : function ()
    {
        Utils.Dom.changeClass(this.oldThis.id,'sb_inactive', 'sb_active');
    },

    __skinButtonOut : function ()
    {
        Utils.Dom.changeClass(this.oldThis.id,'sb_active', 'sb_inactive');
    },

    addHandler : function (obj, event, handler)
    {
        return Utils.Events.addHandler(obj, event, handler.bind(this));
    },

    log : function (v)
    {
        if (console)
            return console.log(v);
        else
            alert(v);
    },

    preventDefault : function (e)
    {
        e.returnValue = false;
        if (e.preventDefault){
            //FF
            e.preventDefault();
        }
    },
    
    showLoading: function ()
	{
        this.fade('Loading...');
    },

    showSaving: function ()
	{
        this.fade('Saving...');
    },

    fade: function (message)
    {
        if (!window.fadePan)
        {
            window.fadePan_counter = 0;
            window.fadePan = document.createElement("iframe");
			window.fadePan.frameBorder = 0;
            window.fadePan.className = 'fade';
			
            window.fadePan.msgBox = document.createElement("div");
            window.fadePan.msgBox.className = 'fadeMsg';

            Utils.Events.addHandler(window.fadePan, "click", this.preventDefault.bind(this));
            Utils.Events.addHandler(window, "resize", this.resizeFade.bind(this));
            document.body.appendChild(window.fadePan);
            document.body.appendChild(window.fadePan.msgBox);
        }
        if (message)
        {
            window.fadePan.msgBox.innerHTML = message;
            window.fadePan.msgBox.style.display = "block";
        }
        else window.fadePan.msgBox.style.display = "none";

        this.setElementOpacity(window.fadePan, 0.5);
        window.fadePan.style.display = "block";
        this.resizeFade();

        window.fadePan_counter ++;
    },
    
    unFade : function (is_force)
    {
        window.fadePan_counter --;
        if (is_force) window.fadePan_counter = 0;
        if (window.fadePan_counter <= 0 && window.fadePan)
        {
            window.fadePan.style.display = "none";
            window.fadePan.msgBox.style.display = "none";
            window.fadePan_counter = 0;
        }
    },
    
    resizeFade: function(is_now)
    {
        var rootNode = document.body.parentNode? document.body.parentNode: document.body;
        window.fadePan.style.width = rootNode.scrollWidth + "px";
        window.fadePan.style.height = rootNode.scrollHeight + "px";
        if (window.fadePan.msgBox.style.display == "block")
        {
            this.setToCenter(window.fadePan.msgBox);
        }
    },
    
    setToCenter: function(box)
    {
        var rootNode = document.body.parentNode? document.body.parentNode: document.body;
        box.style.left = rootNode.scrollLeft + parseInt(rootNode.clientWidth/2) - parseInt(box.offsetWidth/2) + "px";
        box.style.top = rootNode.scrollTop + parseInt(rootNode.clientHeight/2) - parseInt(box.offsetHeight/2) + "px";
        
    },
    
    setElementOpacity: function(sElemId,  nOpacity)
    {
        var opacityProp = this.getOpacityProperty();
        var elem = (typeof(sElemId) == 'object')? sElemId: document.getElementById(sElemId);
        if (!elem || !opacityProp) return;
        if (opacityProp=="filter")
        {
            nOpacity *= 100;
            var oAlpha;
            try{
            oAlpha = elem.filters['DXImageTransform.Microsoft.alpha'] || elem.filters.alpha;
            } catch (e) { }
            if (oAlpha) oAlpha.opacity = nOpacity;
            else elem.style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity="+nOpacity+")";
        }
        else elem.style[opacityProp] = nOpacity;
    },

    getOpacityProperty: function ()
    {
        if (typeof document.body.style.opacity == 'string') return 'opacity';
        else if (typeof document.body.style.MozOpacity == 'string') return 'MozOpacity';
        else if (typeof document.body.style.KhtmlOpacity == 'string') return 'KhtmlOpacity';
        else if (document.body.filters) return 'filter';
        return false;
    },

    jsonRequest: function (type, data, is_silent, mod, par)
	{
        var post = [];
        if (typeof(data) == 'object') {
            for (key in data) post.push(key + '=' + escape(data[key]));
            post = post.join('&');
        }
        else post = escape(data);
        if (!is_silent) this.showLoading();
        var x = new dtmlXMLLoaderObject(this.jsonResponse.bind(this), arguments, true);
        x.is_silent = is_silent;
        var scr;
        if (mod == 'service') scr = 'services.php?type='+type+(par||'');
        else
		{
			scr = mod
				? '?mod=' + mod + '&act=' + type.toLowerCase()+(par||'')
				: '?mod=dataprocessor&name=' + type.toLowerCase() + '&act=get'+(par||'');
		}
    //showMessage('jsonRequest[' + type + ']: post = ' + post, MSG_WARNING);
        x.loadXML(scr + '&time' + (new Date).getTime(), true, post);
    },

    jsonResponse: function (arg, b, c, d, obj)
	{
        var data = null;
		if (arg[3] == 'html') data = obj.xmlDoc.responseText;
		else
		{
			if (!obj.is_silent) this.unFade();
			try {
				eval('data = ' + obj.xmlDoc.responseText);
			}
			catch (e) {
				data = '';
			}
		}
        // saved successfully
        var call_back_function = '__on' + arg[0];
        if (typeof(this[call_back_function]) == 'function') this[call_back_function](data);
        else
        {
            call_back_function = 'on' + arg[0];
            if (typeof(this[call_back_function]) == 'function') this[call_back_function](data);
        }
    },
    
    selectByValue: function (el, value)
    {
        if (el && el.tagName.toLowerCase() == 'select')
        {
            for (var i=0; i<el.length; i++)
            {
                if (el.options[i].value == value) {
                    el.selectedIndex = i;
                    return i;
                }
            }
        }
        return null;
    },
    
    setAction: function (form, params, is_autosubmit)
	{
		if (form && form.act) form.act.value = action;
		else
		{
			var p = this.parseURLparams();
			if (params) for (k in params) p[k] = params[k];
			var action = [];
			for (k in p)
			{
				action.push(k + '=' + escape(p[k]));
			}
			if (form)
			{
				form.setAttribute('action', '?' + action.join('&'));
				if (is_autosubmit) form.submit();
			}
			else window.location.href = '?' + action.join('&');
		}
    },
    
    previewSwf: function (act)
    {
		var url = window.location.protocol + '//';
		url += (window.G_chost? window.G_chost: window.location.host) + '/' +  act;
        this.fade();
        this.setPrewiewFrameSize();
        var fr=document.getElementById('PreviewFrame');
        fr.style.display='block';
        var ifr=fr.getElementsByTagName('IFRAME')[0];
		//new flash
		if(window.G_lock_interface)
			return this.previewSwfStart(url,fr);
			
        ifr.contentWindow.document.body.style.backgroundColor='gray';
        ifr.contentWindow.document.body.style.textAlign="center";
        ifr.contentWindow.document.body.innerHTML=
            '<div style="text-align:center;font-size:120%;font-family:arial;width:100%;height:100%;margin:0;"><div style="height:47%;"></div>'+
                'Processing PDF document... '+
            '</div>'
		ifr.src = url;
    },
	
	// new flash previewer
	previewSwfStart: function(url,el)
	{
		var div=document.createElement('DIV');
		var ifr=el.getElementsByTagName('IFRAME')[0];
		div.style.width=(el.offsetWidth)+'px';
		div.style.height=(el.offsetHeight-20)+'px';
		
		if(ifr){
			el.removeChild(ifr); // delete old iframe (for perfomance)
		}
		div.id='PreviewFrame_main';
		div.innerHTML='<div id="PreviewFrame_cen" align="center" style="font-weight:bold;margin-top:10%;line-height:12px;">Preparing files: <span id="PreviewFrame_main_plabel">begin</span>'
			+'<div style="width:200px;border:solid 1px #000000;padding:1px;height:12px;margin-top:5px;" align="left">'
			+'<div id="PreviewFrame_main_perc" style="width:200px;height:12px;padding:0;display:inline-block;font-size:70%;position:relative;vertical-align:top;" align="center"></div>'
			+'<div id="PreviewFrame_main_progress" style="width:1px;height:12px;background-color:#003366;margin-top:-12px">'
			+'</div></div></div>';
		el.appendChild(div);
		// start
		this.sfwRequest_main = new dtmlXMLLoaderObject(this.previewSwf_onEnd.bind(this), null, true);
        this.sfwRequest_main.is_silent = true;
		this.sfwRequest_main.loadXML(url + '&time' + (new Date).getTime(), true, null);
		// progress status
		setTimeout(this.previewSwf_checkProgress.bind(this),2000);
	},
	
	previewSwf_checkProgress: function()
	{
		this.sfwRequest_progress = new dtmlXMLLoaderObject(this.previewSwf_onProgress.bind(this), null, true);
        this.sfwRequest_progress.is_silent = true;
		this.sfwRequest_progress.loadXML('progress.php?part=swf_convertation&time' + (new Date).getTime(), true, null);
	},
	
	previewSwf_killProcess: function()
	{
		this.sfwRequest_progress = new dtmlXMLLoaderObject(function(){}, null, true);
        this.sfwRequest_progress.is_silent = true;
		this.sfwRequest_progress.loadXML('progress.php?part=swf_convertation&act=reset&time' + (new Date).getTime(), true, null);
	},

	previewSwf_onProgress: function(arg, b, c, d, obj)
	{
		try {eval('data = ' + obj.xmlDoc.responseText);} catch (e) {data = '';}
		var label=$('PreviewFrame_main_plabel');
		if(data&&label&&typeof(data)=='object'){
			var val=data['value'];
			if(val&&(val['code']==0||val['code']==101)){
				if(val['code']==0)
					this.setProgress(val);
				setTimeout(this.previewSwf_checkProgress.bind(this),500);
			}	
		}	
	},
	
	setProgress: function(v)
	{
		var label=$('PreviewFrame_main_plabel');
		var r=(Math.ceil((parseInt(v['current_page'])/parseInt(v['total_pages']))*100));
		var steps=['','wait for free resources','build source','converter started'];
		var txt;
		if(v['total_pages']){
			txt='processing page '+v['current_page']+'/'+v['total_pages']+' '+(v['total_size']?' '+toBytes(v['total_size']):'');
			if(r){
				$('PreviewFrame_main_progress').style.width=(r*2)+'px';	
				$('PreviewFrame_main_perc').innerHTML=r+'%';
			}	
		}
		else
			if(parseInt(v['step'])>0)
				txt=steps[parseInt(v['step'])];
				
		if(r==100)
			txt+=' encoding...';
		if(label&&label.innerHTML!=txt&&txt)
			label.innerHTML=txt;
	},
	
	previewSwf_onEnd: function(arg, b, c, d, obj)
	{
		try {eval('data = ' + obj.xmlDoc.responseText);} catch (e) {data = '';}
		if(typeof(data)=='object'&&data){
			var div=$('PreviewFrame_main');
			if(data['link']){
				div.innerHTML='';
				this.insertFlashObj(div,data['link'],div.offsetWidth,div.offsetHeight,this.sfwPreviewerParams);
			}	
			else {
				var d=data;
				if(data['response'])
					d=data['response'];
				$('PreviewFrame_cen').innerHTML='<b>'+('Error '+d['code']+': '+d['msg'].replace('Exec error: ',''))+'</b>';
			}
		}
	},
	
	sfwPreviewerParams:{
		'skip_login':1,
		'allowFullScreen':'true',
		'search':1,
		'hview':1,
		'vview':1
	},
	
	insertFlashObj: function(node, url, width, height, params) {
	  var object, param, key;
	  function newParam(name, value) {
		if(0 /*@cc_on + 1 @*/) return ['<PARAM name="', name, '" value="', value, '" />'].join('');
		else {
		  param = document.createElement('param');
		  param.name = name;
		  param.value = value;
		  return param;
		}
	  }
	  if(0 /*@cc_on + 1 @*/) {
		object = ['<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="', width, '" height="', height, '"><PARAM name="movie" value="', url, '" />'];
		if(params) for(key in params) if(params.hasOwnProperty(key)) object.push(newParam(key, params[key]));
		object.push('</OBJECT>');
		node.innerHTML = object.join('');
	  }
	  else {
		object = document.createElement('object');
		object.type = 'application/x-shockwave-flash';
		object.data = url;
		object.width = width;
		object.height = height;
		if(params) for(key in params) if(params.hasOwnProperty(key)) object.appendChild(newParam(key, params[key]));
		while(node.firstChild) node.removeChild(node.firstChild);
		node.appendChild(object);
	  }	
	},
	
	
    //
    previewImg: function(act)
    {
		var url = window.location.protocol + '//';
		url += (window.G_chost? window.G_chost: window.location.host) + '/' +  act;
        this.fade();
        this.setPrewiewFrameSize();
        var fr=document.getElementById('PreviewFrame');
        fr.style.display='block';
		fr.style.backgroundColor='gray';
        var ifr=fr.getElementsByTagName('IFRAME')[0];
		ifr.contentWindow.document.body.style.overflow='hidden';
        ifr.contentWindow.document.body.style.backgroundColor='gray';
        ifr.contentWindow.document.write(
            '<html><body style="overflow:auto;text-align:center;margin:0;padding:0;width:100%;height:100%;">'+
			'<div style="position:absolute;font-size:120%;font-family:arial;top:45%;left:45%;" id="loadLabel">Loading Image...</div>'+
            '<div style="text-align:center;width:100%;height:100%;margin:0;background-color:gray;overflow:visible;">'+
                '<img src="' + url + '" alt="" onload="document.getElementById(\'loadLabel\').style.display=\'none\'" />'+
            '</div></body></html>');    
    },
    
    setPrewiewFrameSize : function ()
    {
		  function IEVersion()
          {
                var ind=navigator.userAgent.indexOf('MSIE');
                var buf=null;
                if (ind>0)
                {
                    buf=navigator.userAgent.substr(ind);
                    buf=buf.substr(0,buf.indexOf(';'));
                    buf=buf.replace('MSIE',"");
                    buf=buf.replace(' ','');
                    buf=buf.substr(0,buf.indexOf('.'));
                }
                return parseInt(buf);
         }
         var IE6=(IEVersion()&&IEVersion()<7)?true:false;
        
      var rootNode = document.body.parentNode? document.body.parentNode: document.body;
      var PF=document.getElementById('PreviewFrame');
      PF.style.position=IE6?'absolute':'fixed';
      var pw=(parseInt(rootNode.clientWidth)-30);
      var ph=(parseInt(rootNode.clientHeight)-30);
      PF.style.width=pw+'px';
      PF.style.height=ph+'px';
      PF.style.left=((IE6?rootNode.scrollLeft:0)+15)+'px';
      PF.style.top=((IE6?rootNode.scrollTop:0)+15)+'px';
      var ifr=PF.getElementsByTagName('IFRAME')[0];
	  if(ifr){
		ifr.style.width=(pw-3)+'px';
		ifr.style.height=(ph-20) + "px";  
	  }
      //& set draggable
      var dwind=new dynamicWindow('PreviewFrame');
      if (dwind.currentWindow!=null) return;
      dynamicWindowObjectLink=dwind;      
      dwind.currentWindow=document.getElementById(dwind.id);
      dwind.addDraggingElements(['previewFrameLineEl1','previewFrameLineEl2']);
      dwind.onStartDrag=function(){ page.PFSheet('block'); };
      dwind.onStopDrag=function(){ page.PFSheet('none'); };
      dwind.setDraggable();  
      
    },
    
    PFSheet: function(flag)
    {
        var pfs=document.getElementById('PFSheet');  
        pfs.style.display=flag;
    },   
    
    previewClose: function ()
    {
        this.unFade();
		var fr = document.getElementById('PreviewFrame'); 
        if (!fr) return;
		
		if(this.sfwRequest_progress)
			this.sfwRequest_progress.xmlDoc.abort();
				
		if(this.sfwRequest_main){
			this.sfwRequest_main.xmlDoc.abort();
			this.previewSwf_killProcess();	
		}	
			
		if($('PreviewFrame_main'))
			fr.removeChild($('PreviewFrame_main'));
		
        var ifr = fr.getElementsByTagName('IFRAME')[0];
		if(ifr){
			ifr.src = "about:blank";
			if (ifr.stop) ifr.stop();	
		}
		fr.style.left="-999px";
		fr.style.top="-999px";
		//fr.style.display='none';
    },
    
    parseURLparams: function (url)
	{
        var out = {};
        var t = location.search.substr(1).split('&');
        for (var i=0; i<t.length; i++)
		{
            var p = t[i].split('=');
            out[p[0]] = unescape(p[1]);
        }
        return out;
    },
	
	getElementsByClassName: function(className, parent)
	{
		var out = [];
		var parent = parent || document.body;
		var els = parent.getElementsByTagName('*');
		for (var i=0; i<els.length; i++)
		{
			var el = els[i];
			if (el.className.indexOf(className) != -1) out.push(el);
			
		}
		return out;
	},

	setCookie: function(name, value, cookie_param)
	{
		var str = name + "=" + value + (cookie_param? (";" + cookie_param): "");
		document.cookie = str;
	},
	
	delCookie: function(cookie_name)
	{
		var cookie_date = new Date();  // current date & time
		cookie_date.setTime (cookie_date.getTime() - 1);
		document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();			
	},
	
	getCookie: function(cookie_name)
	{
		var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
		if (results) return unescape(results[2]);
		else return null;
	}
});

function createPage(cNew)
{
	if (!self._clazzes) self._clazzes = [cPage];
	var cFrom = self._clazzes[self._clazzes.length - 1];
	var cCurrentPage = newClass(cFrom, cNew);   
    self.page = new cCurrentPage();
	self._clazzes.push(cCurrentPage);
}

Utils.Events.addHandler(window, "load", function()
{
	if (window.page) window.page.onLoad();
});

createPage(cPage);

/**
*	New Class Paginator
**/
function Paginator()
{
	// init vars
	this.max_links = 8;
	//
	this.page_num = 1;
	this.total_pages = 1;
	this.ipp = 10;
	this.total_items = 1;
	this.page_items = 1;
	
	this.pg_cons = [];
	this.stat_cons = [];
}

Paginator.prototype.onPageClick = function(page)
{
	alert('Warning: Method `onPageClick` is undfined!\n\nPage #' + page + ' has been selected.');
}

Paginator.prototype.setAttributes = function(attrs)
{
	// set new attributes
	if (attrs)
	{
		var aval_attrs = ['page_num', 'total_pages', 'ipp', 'total_items', 'page_items'];
		for (var i=0; i < aval_attrs.length; i++)
		{
			var key = aval_attrs[i];
			if (attrs[key] !== window.undefined) this[key] = attrs[key];
		}
	}
}

Paginator.prototype.setHandler = function(name, func)
{
	if (typeof(func) == 'function' && typeof(this[name]) == 'function') this[name] = func;
}

Paginator.prototype.renderPager = function(con)
{

	var self = this;
 	con = $(con);
	con.innerHTML = ''; // clear console
	// Previous button
	var btn_prev = document.createElement('a');
		btn_prev.innerHTML = '&lt;Prev';
		btn_prev.setAttribute('href', 'javascript:void(0)');
		if (this.page_num == 1) btn_prev.className = 'disabled';
		else
		{
			btn_prev.title = "Go page #" + (self.page_num - 1);
			btn_prev.onclick = function()
			{
				self.onPageClick(self.page_num - 1);
			};
		}
	con.appendChild(btn_prev);
//console.log(btn_prev.onclick);
//btn_prev.onclick();

	// Separator
//	con.appendChild(document.createTextNode('|'));

	// First button
	var btn_first = document.createElement('a');
		btn_first.innerHTML = '1';
		btn_first.setAttribute('href', 'javascript:void(0)');
		if (this.page_num < 2) btn_first.className = 'active';
		btn_first.title = "Go page #1";
		btn_first.onclick = function()
		{
			self.onPageClick(1);
		};
	con.appendChild(btn_first);

	var first_vis_link = this.page_num - Math.ceil(this.max_links/2) + 1;
	if (first_vis_link > this.total_pages - this.max_links) first_vis_link = this.total_pages - this.max_links;
	if (first_vis_link < 2) first_vis_link = 2;

	// Separator
	if (first_vis_link > 2) con.appendChild(document.createTextNode('...'));

	for (var i = first_vis_link; i < first_vis_link + this.max_links; i++)
	{
		if (i >= this.total_pages) break;
		// Last button
		var btn_page = document.createElement('a');
			btn_page.innerHTML = i;
			btn_page.setAttribute('href', 'javascript:void(0)');
			if (this.page_num == i) btn_page.className = 'active';
			btn_page.title = "Go page #" + i;
			btn_page.onclick = function()
			{
				self.onPageClick(parseInt(this.innerHTML));
			};
		con.appendChild(btn_page);
	}

	// Separator
	if (first_vis_link + this.max_links < this.total_pages - 1) con.appendChild(document.createTextNode('...'));
	
	if (this.total_pages > 1)
	{
		// Last button
		var btn_last = document.createElement('a');
			btn_last.innerHTML = this.total_pages;
			btn_last.setAttribute('href', 'javascript:void(0)');
			if (this.page_num == this.total_pages) btn_last.className = 'active';
			btn_last.title = "Go page #" + self.total_pages;
			btn_last.onclick = function()
			{
				self.onPageClick(self.total_pages);
			};
		con.appendChild(btn_last);
	}
	// Separator
//	con.appendChild(document.createTextNode('|'));

	// Next button
	var btn_next = document.createElement('a');
		btn_next.setAttribute('href', 'javascript:void(0)');
		btn_next.innerHTML = 'Next&gt;';
	con.appendChild(btn_next);
	if (this.page_num >= this.total_pages) btn_next.className = 'disabled';
	else
	{
		btn_next.title = "Go page #" + (self.page_num + 1);
		btn_next.onclick = function()
		{
			self.onPageClick(self.page_num + 1);
		};
	}
}

Paginator.prototype.renderStat = function(con)
{
	var self = this;
	var con = $(con);
	
	if (this.page_items > 0)
	{
		var item_first = (this.page_num - 1) * this.ipp;
		con.innerHTML = (item_first + 1) + '-' + (item_first + this.page_items) + '/' + this.total_items;
	}
	else con.innerHTML = '0/0';
}