var G = { SEARCH_URL : '/result.php', q :null, type:null };
window.onerror = function (a,b,c)
 {
 	var s = a + ' ' + b + ' '+ c;
 	if( window['console']){
		console.log(s);
 	}
 	else
 	{
 		alert( s);
	}
 }

function var_dump(obj)
{
	var s = '';
	for( var x in obj )
	{
		s += "\n" + x + " : " ;
		if( 'function' == typeof obj[x] ){
			s += 'function(){...}';
		}else{
			s += obj[x].toString();
		}
	}
	alert( s );
}

String.prototype.trim = function () {return this.replace(/^\s+/, "").replace(/\s+$/, "");}
function $2(id){ return document.getElementById(id); }

var Srch =
{
	txt:'Enter Keyword',
	onFocus:function()
	{
		if( G.q )
		{
			var q = G.q;
			q.value = q.value.trim();
			if( Srch.txt == q.value )
			{
				q.value = '';
			}
			q.style.color='#000000';
		}
	},
	onBlur:function(){
		if( G.q ){
			var q = G.q;
			q.value = q.value.trim();
			if( '' == q.value )
			{
				q.value = Srch.txt;
				q.style.color='#bebebe';
			}
		}
	}
}

function Event(evt)
{
	this.e= null
	this.target = null;
	this.tag = '';
	this.text='';

	this.init = function ()
	{
		this.e = evt||window.event;

		if( null != this.e )
		{
			this.target = this.e.target||this.e.srcElement;
			this.tag = this.target.nodeName.toUpperCase();
			this.text = this.target.textContent || this.target.innerText;
		}
		//var_dump( this );
	};

	this.StopPropagation = function()
	{
		var e = this.e;
    		if( e && e.stopPropagation) e.stopPropagation(); //ff
    		else if(window.event)window.event.cancelBubble = true; //ie
	};

	this.init( evt );
}



function parseURL(url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
        //source: url,
        //protocol: a.protocol.replace(':',''),
        //file: (a.pathname.match(/\/([^\/?#]+)$2/i) || [,''])[1],
        //hash: a.hash.replace('#',''),
        //path: a.pathname.replace(/^([^\/])/,'/$21'),
        //relative: (a.href.match(/tp:\/\/[^\/]+(.+)/) || [,''])[1],
        //segments: a.pathname.replace(/^\//,'').split('/'),
        host: a.hostname,
        //port: a.port,
        //query: a.search,
        params: (function(){
            var ret = {},
                seg = a.search.replace(/^\?/,'').split('&'),
                len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = unescape( s[1] );
            }
            return ret;
        })()
    };
}

function jscss(o,c1,a,c2)
{
    //Modify class fo robjects
    //o = object, c1=class1 c2=class2 a=swap|add|remove|check
    a  = a||'add'; // Optional , default add
    c2 = c2||'';  //Optional, default ''
    switch (a){
        case 'swap':
        o.className=!jscss(o,c1,'check')?o.className.replace(c2,c1): o.className.replace(c1,c2);
        break;
    case 'add':
        if(!jscss(o,c1,'check')){o.className+=o.className?' '+c1:c1;}
        break;
    case 'remove':

        var rep=o.className.match(' '+c1)?' '+c1:c1;
        o.className=o.className.replace(rep,'');
        break;
    case 'check':
        return new RegExp('\\b'+c1+'\\b').test(o.className)
        break;
    }
}

var tab =
{
	tabCount: 0,
	tabPar:null,
	conPar:null,
	currTp:'web',

	init:function()
	{

		this.tabPar =  $2('div_parent_tab');
		this.conPar = $2('div_parent_content');
		if( this.conPar )
		{
			this.tabCount = this.conPar.childNodes.length;
		}

	},

	getId:function(q, tp)
	{
		var el = tmpstr = '';

		//if(G.type.value == 'jobs')
		if(tp == 'jobs')
		{
			var l = $2('zp_l').value.trim();
			el = escape(  unescape(  l.trim() ).replace(/ /g, '+')  );
			tmpstr = '_'+el;
		}
		var eq =  escape(  unescape(  q.trim() ).replace(/ /g, '+')  );
		var ret = { 'tid' : 'div_' + eq + '_' + tp + tmpstr + '_tab' , 'cid': 'div_' + eq + '_' + tp + tmpstr + '_child_content' };
		return ret;
	},
	findParamFromTabId:function(str){


		l= str.length;
		str = str.substring(4,l-4);
		ar = {};
		l= str.length;
		tsptr = str.lastIndexOf('_');
		ar[1]= str.substring(0, tsptr);
		ar[2] = str.substring(tsptr+1, l);
		return ar;
	},

	remove:function( q, tp )
	{
		if( 1 >= this.tabCount )
		{
			return;
		}

		var aid = this.getId( q, tp );
		var ot = document.getElementById( aid['tid'] );
		var oc = document.getElementById( aid['cid'] );

		var activateFirst  = false;

		if( jscss( ot, 'cur', 'check') )
		{
			activateFirst = true;
		}

		var p = ot.parentNode;
		p.removeChild( ot );

		p = oc.parentNode ;
		p.removeChild( oc );
		this.tabCount--;
		this.setCloseLink();

		if( activateFirst )
		{
			this.activateFirst();
		}
	},

	activateFirst : function ()
	{
		var o = this.tabPar.getElementsByTagName('DIV');
		if( o )
		{
			if( 0 < o.length )
			{
				var id = o[0].id
				//var ar = id.split('_');
				var ar = tab.findParamFromTabId(id);
				//if( 2 <= ar.length )
				if( undefined != ar[1] && undefined != ar[2] )
				{
					tab.activate( ar[1], ar[2] );
				}
			}
		}
	},

	add:function ( q, tp , h )
	{
		q = q.trim();
		if( Srch.txt == q )
		{
			return false;
		}

		var aid = this.getId(q, tp );

		this.setTitle( q, tp, aid['tid'] );
		this.setContent(q, tp, aid['cid'], h );
		this.activate(q, tp);
		//this.updateContent(q, tp, h );
	},

	setTitle: function (q, tp , tid)
	{
		var ot = $2(tid) ;
		if( null == ot )
		{
			//var id = 'div_' + eq + '_' + tp + '_child_content';
			ot = document.createElement('div');
			ot.id = tid;
			ot.className = 'tab';
			ot.style.float = 'left';

			if( 7 < q.length )
			{
				q = q.substring(0, 6)  +  '...';
			}
			//q =  q.replace(' ', '+');

			var h ='';

			h += '<div class="s' + tp + '"><div class="selected_text">';
			h += '<a onclick="return oncloseTab(this)" href="#close" class="ra">x</a>';
			h += '<a onclick="return onclickTab(this);" href="#open" class="la">' + q + '</a>';
			h += '</div></div>';

			ot.innerHTML = h;
			this.tabPar.appendChild( ot );
			this.tabCount++;
			this.setCloseLink();
		}
		return ot;
	},

	setContent: function ( q, tp, cid, h )
	{
		var oc = $2(cid);
		if( null == oc)
		{
			oc = document.createElement('div');
		}
		oc.style.display = 'none';
		oc.id = cid;
		oc.className = "div_child_content";
		oc.innerHTML = h;
		this.conPar.appendChild( oc );
		return oc;
	},

	activate: function ( q, tp )
	{

		var aid = this.getId( q, tp );
		this.currTp=tp;
		var l = this.conPar.childNodes.length;
		var i=0;
		for(i=0; i<l; i++)
		{
			if( 'DIV' == this.conPar.childNodes[i].nodeName )
			{
				if( aid['cid'] == this.conPar.childNodes[i].id )
				{
					this.conPar.childNodes[i].style.display =  '';
				}
				else
				{
					this.conPar.childNodes[i].style.display =  'none';
				}
			}
		}

		var l = this.tabPar.childNodes.length;
		var i=0;
		for(i=0; i<l; i++)
		{
			if( 'DIV' == this.tabPar.childNodes[i].nodeName )
			{
				if( aid['tid'] == this.tabPar.childNodes[i].id )
				{
					jscss( this.tabPar.childNodes[i] , 'cur', 'add' );


				}
				else
				{
					jscss( this.tabPar.childNodes[i] , 'cur', 'remove' );
				}
			}
		}

		if(tp == "web")
		{
			$2('total_results').style.display = 'block';;
		}
		else
		{
			$2('total_results').style.display = 'none';;
		}
	},

	addAjaxResp:function ( q, tp , p, makeNewCall , url , extraParam )
	{
		//G.q.focus();
		/*for jobs*/
		if(G.type.value == "jobs")
		{
			$2('zp_q').focus();
		}else
		{
		G.q.focus();
		}

		p = p || 1;

		makeNewCall = makeNewCall || false; //Make new Ajx Call
		url = url || G.SEARCH_URL + '?' ;
		extraParam = extraParam || {};
		q = q.trim();
		if( ('' == q ) || ( Srch.txt == q ) )
		{
			return;
		}

		if( (null == this.tabPar) || ( null == this.conPar ) )
		{
			this.init();
		}

		if( (null == this.tabPar) || ( null == this.conPar ) )
		{
			location.href = url + 'q='+encodeURIComponent(q) + '&type='+tp;//+'&qt='+qt+'&rs=1';
			return;
		}

		var aid = this.getId(q, tp);
		var ajxLoader = '<div class="xhr">&nbsp;</div>';

		if( null == $2(aid['cid']) )
		{
			this.add(q, tp, ajxLoader );
			makeNewCall = true;
		}

		if( makeNewCall )
		{
			var rp = {};
			rp['q'] = q;
			rp['type'] = tp;
			rp['ajax'] = 1;
			rp['p'] = p;
			//rp['qt'] = qt;
			rp['dt']  = new Date().getTime();
			rp['s']=1;

			rp['l']=$2('zp_l').value.trim()

			for(var xk in extraParam)
			{
				rp[xk]=extraParam[xk];
			}

			$2(aid['cid']).innerHTML = ajxLoader;


			Ajax.updater( url , rp, aid['cid'] );
		}
		else
		{
			tab.activate( q, tp );
		}
	},
	setCloseLink:function()
	{
		switch( this.tabCount)
		{
			case 1:
				jscss(this.tabPar.childNodes[0], 'single', 'add');
				break;
			case 2:
				jscss(this.tabPar.childNodes[0], 'single', 'remove');
				break;
			default:
		}
	}
};
//END TAB OBJECT

var Ajax =
{
	updater : function ( url, param, id )
	{
		var x = this.getXHR(), k, sparam='';
		var ajx = this;

		url = url.trim();
		if( '?' != url.substr( url.length-1, 2) )
		{
			url += '?';
		}
		else
		{
			url += '&';
		}

		for( k in param)
		{
			sparam += encodeURIComponent(k) + '=' + encodeURIComponent(param[k]) + '&';
		}
		//x.open("GET", url + sparam ,true);
		x.open("POST", url ,true);
		x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		x.onreadystatechange = function()
		{
			if(x.readyState == 4 )
			{
				var js, i, l, c = $2(id);
				c.innerHTML = x.responseText;
				window['js']= js = c.getElementsByTagName('pre')
				l=js.length;
				for(i=0; i<l; i++)
				{
					//alert( js[i].innerHTML );
					try{
						eval(  js[i].innerHTML );
					}catch(e){}
				}
				ajx.gaTracking(url+sparam);

			}
		}
		x.send(sparam);
	},

	getXHR : function()
	{
		var o = false;
		if(window.XMLHttpRequest && !(window.ActiveXObject))
		{
			try
			{
				o = new XMLHttpRequest();
			}
			catch(e)
			{
				o = false;
			}
		}
		else if(window.ActiveXObject)
		{
			try
			{
				o = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e)
			{
				try
				{
					o = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(e)
				{
					o = false;
				}
			}
		}
		return o;
	},

	gaTracking : function(url)
	{
		try {
			var pageTracker = _gat._getTracker("UA-9570932-20");
			pageTracker._trackPageview(url);
			} catch(err) {}
	}

};

function onclickTab( obj )
{
	try
	{
		G.q.focus();
	}
	catch(e)
	{}

	//var ar = obj.parentNode.parentNode.parentNode.id.split('_');
	var ar = tab.findParamFromTabId(obj.parentNode.parentNode.parentNode.id);
	tab.activate( ar[1], ar[2] );
	return false;
}

function oncloseTab( obj )
{
	//var ar = obj.parentNode.parentNode.parentNode.id.split('_');
	var ar = tab.findParamFromTabId(obj.parentNode.parentNode.parentNode.id);
	tab.remove( ar[1], ar[2] );
	return false;
}

function onclickGo(frm)
{
	var q = G.q;
	//q.value = q.value.trim();
	if(G.type.value == "jobs")
	{
		q.value = $2('zp_q').value.trim();
		$2('zp_q').focus();
	}
	else
	{
		q.value = G.q.value.trim();
		G.q.focus();
	}
	if( '' != q.value )
	{
		tab.addAjaxResp(q.value, G.type.value);
	}
	return false;
}

function onclickLink(obj, tp)
{
	var lnks = ['aw', 'an', 'ai', 'av', 'tw', 'jb'], i=0, l, par;

	par = obj.parentNode ||  obj.parentElement;
	tp = par.id;

	l = lnks.length
	for(i=0; i<l; i++)
	{
		lnk = G[lnks[i]];
		par = lnk.parentNode ||  lnk.parentElement;
		par.className = ( lnk.id == obj.id ) ? 'searchSelected' : 'searchLinks';
	}

	G.type.value =tp;
	if(G.type.value == "jobs")
	{
		$2('regular_sb').style.display='none';
		$2('zpSearchFor').style.display='block';
	}
	else
	{
		$2('regular_sb').style.display='block';
		$2('zpSearchFor').style.display='none';
	}
	if(G.type.value == "jobs")
	{
		G.q.value = $2('zp_q').value.trim();
	}
	else
	{
		G.q.value = G.q.value.trim();
	}


	if( ('' == G.q.value) || (Srch.txt == G.q.value))
	{
		G.q.value = '';
	}
	Srch.onFocus();
	try
	{
		//document.forms['frmsearch']['q'].focus();

	}catch(e){}

	tab.addAjaxResp( G.q.value, tp);
	return false;
}

function onclkRelQ( evt )
{
	var ret = true, e = new  Event(evt);
	if( null != e.target )
	{
	    	if('A' ==  e.tag )
	    	{
	    		if( '' == e.target.className)
	    		{
				var q = e.text;
				tab.addAjaxResp( q,  tab.currTp );
				e.StopPropagation(); //cancling event for further progress
				e = null;
	    		}
	    	}
	    	ret = false;
	}
	return false;
}

function moreLess( obj, id )
{
	if( 'more' == obj.className )
	{
		$2(id).style.display='';
		obj.className = 'less';
		obj.innerHTML = obj.innerHTML.replace('More', 'Less');

	}
	else
	{

		$2(id).style.display='none';
		obj.className = 'more';
		obj.innerHTML = obj.innerHTML.replace('Less', 'More');
	}
	return false;
}

function onclkPgn( evt  )
{
	var ret = true, e = new  Event(evt);
	if( null != e.target )
	{
	    	if('A' ==  e.tag)
	    	{
			var aurl = parseURL( e.target.href);

			var tp = aurl['params']['type'] || G.type.value;
			var p = aurl['params']['p'] || 1;
			var q = aurl['params']['q'] || '';

			if( aurl['params']['type']  ) { delete( aurl['params']['type'] ); }
			if( aurl['params']['p']  ) { delete( aurl['params']['p'] ); }
			if( aurl['params']['q']  ) { delete( aurl['params']['q'] ); }

			tab.addAjaxResp( q, tp, p, true ,  '', aurl['params'] );
			e.StopPropagation(); //cancling event for further progress
			e = null;
			ret = false;
	    	}
	}
	return ret;
}

function screenLockUnloack( show_flag, url , aw, ah )
{
    //Lock The Screen With Totaly Transparent DIV,
    //DIv's sed in Locking Screen are Generated On Runtime if Not Found in Source Code
    var l1 = window['l1'] || document.getElementById("l1");
    var l2 = window['l2'] ||document.getElementById("l2");
    if( !l1 )
    {
        l1 = document.createElement('DIV');
        l1['id'] = 'l1';
        l1['className'] = 'l1';
        document.body.appendChild( l1 );

        l2 = document.createElement('DIV');
        l2['id'] = 'l2';
        l2['className'] = 'l2';
        document.body.appendChild( l2 );
    }

    window['l1'] = l1;
    window['l2'] = l2;
    if( show_flag )
    {
    	$2('q').focus();
	l2['innerHTML'] = '<iframe src="'+url+'"  width="'+aw+'" scrolling="no" height="'+ah+'" frameborder="0"></iframe>';
        var w = screen.availWidth, h = screen.availHeight;
        //var ml = ((w-aw)/2.5), mt = ((h-ah)/4);
        var ml = ((w-aw)/2), mt = 100;

        var scrolly = typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement.scrollTop;
        var scrollx = typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement.scrollLeft;
        l2.style.top = (scrolly + mt) + "px";
        l2.style.left= ml  + "px";
        l2.style.display = "block";

        l1.style.width =w + "px";
        l1.style.height = h + "px";
        l1.style.display = "block";
    }
    else
    {
        l1.style.display = 'none';
        l2.style.display = 'none';
    }
}

function onOvrRQ( evt )
{
	var ret = true, e = new  Event(evt);
	if( null != e.target )
	{
	    	if('A' ==  e.tag)
	    	{
	    		var t = e.target;
	    		if( 'more' != t.className )
	    		{
	    			var a = parseURL( t.href );
				if( a.params.q )
				{
					a.params.q = a.params.q.replace(/\+/g, ' ');
			    		t.setAttribute('alt', a.params.q);
			    		t.setAttribute('title',a.params.q);
				}
	    		}
	    	}
	}
}

var CookieObj = {
	createCookie : function (name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	},
	readCookie : function (name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	},
	createCookieForvBt : function (name,value,timestamp) {
		date = new Date(timestamp*1000.0);
		var expires = "; expires="+date.toGMTString();
		document.cookie = name+"="+value+expires+"; path=/";
	}
};
function onMdwn(obj,path,sx)
{
	ck = CookieObj.readCookie('vfyBot');
	if( '1' != ck)
	{
		return true;
	}
	obj.href='http://'+path;
	obj.target = "_blank";

	return true;
}

function onMdwn_new(obj,sx)
{
	ck = CookieObj.readCookie('vBt');
	var _href = obj.href;
	var _rel = obj.getAttribute('rel');

	if( null == ck)
	{
		showUrl(obj, 'display' );
	}
	else
	{
		var qCount = 5;
		var dCount = 10;

		var qCheckT = 300; //5 min
		var dCheckT = 86400; // 1 day


		var totalCount = 0;

		var vCt = CookieObj.readCookie('vCt');

		var cTime = Math.round(new Date().getTime()/1000.0);
		var dfTime = parseInt(ck) - cTime;


		if(! isNaN(vCt) )
		{
			totalCount = parseInt(vCt);
		}

		//quick block
		if (totalCount > dCount )
		{
			showUrl(obj, 'display' );
		}
		else
		{
			//REad 5 min cookie
			var _qcount = 0;
			var qCt = CookieObj.readCookie('qCt');
			var qBt = CookieObj.readCookie('qBt');

			if( (null != qCt) && !isNaN(qCt) )
			{
				_qcount = parseInt(qCt);
			}

			if( null == qCt )
			{
				qCt = 1;
				qBt = cTime;
				CookieObj.createCookieForvBt('qBt', cTime+qCheckT,cTime+qCheckT);
				CookieObj.createCookieForvBt('qCt', '1',cTime+qCheckT);
			}
			else
			{
				var newqcount = _qcount+1;
				CookieObj.createCookieForvBt('qCt', newqcount,qBt);
			}

			if ( _qcount >= qCount )
			{
				showUrl(obj, 'display' );
			}
			else
			{
				showUrl(obj, 'clk' );
			}
		}
		var newCount = parseInt(totalCount) + 1;
		CookieObj.createCookieForvBt('vCt', ''+newCount+'',ck);

	//obj.href='http://'+path;
	obj.target = "_blank";
	}

	return true;
}

function showUrl(obj, type )
{
	var _href = obj.href;
	var _rel = obj.getAttribute('rel');
	var currentFormat = 'display';
	if ( 0 == _rel.indexOf('http://') )// click url is set
	{
		currentFormat = 'clk';
	}
	if ( 'clk' == type )
	{
		//show click url
		if ( 'clk' == currentFormat ){
			return true;
		}
		else{
			var _xhref = _href;
			obj.href = 'http://'+_rel;  // change it to click url
			obj.setAttribute("rel",_xhref);
			return true;
		}
	}
	else
	{
		if('display' == currentFormat )
		{
			return true;
		}
		else
		{
			var _xhref = _href;
			obj.href = _rel;  // change it to click url

			var _xhrefLen = _xhref.length;
			_rel = _rel.slice(7, _xhrefLen);

			obj.setAttribute("rel",_rel);
			return true;
		}

		//show display url
	}
}
