var error_good = new Array();
var error_fields = new Array();
var error_ids = new Array();
var all_elements = new Array();
var error_elements = new Array();
var error_popup_obj = null;
var parent_popup_obj = null;

//----- declarate jQuery ----
if (typeof(jQuery) != 'undefined'){
    var $j = jQuery;
}
//----- declarate jQuery ----

/*
menu_help = new Image();
menu_help.src="/images/menu_help_rol.gif";
menu_proteam = new Image();
menu_proteam.src="/images/menu_proteam_rol.gif";
menu_carrermatch = new Image();
menu_carrermatch.src="/images/menu_carrermatch_rol.gif";
menu_bluepages = new Image();
menu_bluepages.src="/images/menu_bluepages_rol.gif";
menu_communicate = new Image();
menu_communicate.src="/images/menu_communicate_rol.gif";
menu_myprofile = new Image();
menu_myprofile.src="/images/menu_myprofile_rol.gif";
menu_myoffice = new Image();
menu_myoffice.src="/images/menu_myoffice_rol.gif";
*/
message_box = new Image();
message_box.src="/images/message_box.jpg";
button_chat_rol = new Image();
button_chat_rol.src="/images/button_chat_rol.jpg";
button_networks_rol = new Image();
button_networks_rol.src="/images/button_networks_rol.jpg";
button_conference_rol = new Image();
button_conference_rol.src="/images/button_conference_rol.jpg";
button_go_rol = new Image();
button_go_rol.src="/images/button_go_rol.jpg";


if (typeof(soundManager) != 'undefined'){
    // initialize the sound manager
    soundManager.url = '/swf/';
    soundManager.debugMode = false;


    soundManager.onready(function(oStatus) {
        if (oStatus.success) {
            soundManager.createSound({id: 'msg_in', url: '/sound/1.mp3'});
            soundManager.createSound({id: 'conf_room_msg_in', url: '/sound/2.mp3'});
        }
    });
}

function requestJsonToObject(request) {
    return eval( '(' + request.responseText + ')' );
}

function htmlEnc(str) {
  try {
    str = str.replace(/&/g,"&amp;");
    str = str.replace(/</g,"&lt;");
    str = str.replace(/>/g,"&gt;");
    str = str.replace(/\"/g,"&quot;");
    str = str.replace(/\n/g,"<br />");
    return str;
  } catch (e) {
    return null;
  }
}

function submenu (element) {
    if (element.style.display == 'none')
    {
        element.style.display = '';
    }
    else
    {
        element.style.display = 'none';
    }
}

function validateSearchForm(obj) {
    if($j.trim(obj.searchString.value).length == 0) {
        Dialog.alert('Please enter search criteria.', {width: 250, className:"alphacube"})
        return false;
    }
    return true;
}



function SetCookie(cookieName,cookieValue,nDays) 
{
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) {
    document.cookie = cookieName+"="+escape(cookieValue)
                 + ";path=/";
 } else{
     expire.setTime(today.getTime() + 3600000*24*nDays);
     document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+ expire.toGMTString() + ";path=/";
} 
}

 

function getCookie(name) 
{
   	var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);

    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}


function getRandom() {
    a = Math.random() + '';
    return a.replace('.', '');
}

function getRandomNum(lbound, ubound)
{
    return (Math.floor(Math.random() * (ubound - lbound)) + lbound);
}

function setPagingLimit(value)
{
    var current_url = document.location.href;
    var url = current_url.replace(/(\?|&)page=\d+/, '');
    url = url.replace(/(\?|&)limit=\d+/, '');
    url += '?limit=' + value;
    document.location.href = url;
}


function getRandomChar()
{
    var numberChars = "0123456789";
    var lowerChars = "abcdefghijklmnopqrstuvwxyz";
    var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var otherChars = "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/? ";
    var charSet = numberChars;
    charSet += lowerChars;
    charSet += upperChars;
  
    return charSet.charAt(getRandomNum(0, charSet.length));
}

function getPassword(length)
{
    var rc = "";
    if (length > 0)
        rc = rc + getRandomChar();
        
    for (var idx = 1; idx < length; ++idx)
    {
        rc = rc + getRandomChar();
    }
    return rc;
}

function generatePassword( destin_ids ) 
{
    var length = 8;
    var pwd = getPassword( length );
    for ( var i = 0; i < destin_ids.length; i++ )
        document.getElementById(destin_ids[i]).value = pwd;
}

function my_field_error(element, errorMessage)
{
    if ( errorMessage )
    {
        element.style.backgroundColor = "#FFEE00";
        top.error_fields.push(errorMessage);
    }
    else
    {
        element.style.backgroundColor = "#FFF";
    }
}


function spinControl(name, step, min, max)
{
    var elem = document.getElementsByName(name)[0];
    if ( elem )
    {
        var nextVal = parseInt(elem.value) + step;
        if ( nextVal < min )
        {
            elem.value = min;
            return;
        }
        if ( nextVal > max )
        {
            elem.value = max;
            return;
        }
        elem.value = nextVal;
    }
}

function showPopup(str, x, y)
{
    var str3 = 'location=no,menubar=no,toolbar=no,dependent=yes,dialog=yes,modal=yes,alwaysRaised=yes,resizable=yes,status=no,scrollbars=yes,';
    
    if (y < (screen.availHeight - 20))
        str3 += 'width=' + x + ',height=' + y + ',left=' + ((screen.availWidth-x)/2) + ',top=' + (screen.availHeight-y)/2;
    else 
        str3 += 'width=' + (x + 20) + ',height=' + (screen.availHeight - 50) + ',left=' + ((screen.availWidth-x)/2) + ',top=10';    
    var newWindow = window.open(str, null, str3);
    newWindow.focus();
}

function writeBookmarkLink(url, title)
{
	try {
		if (window.sidebar) { // Mozilla Firefox Bookmark
			return document.write('<a href="javascript:createBookmarkLink(\'' + url + '\', \'' + title + '\')");">Bookmark this page</a>'); 
		} else if (window.external) { // IE Favorite
			return document.write('<a href="javascript:createBookmarkLink(\'' + url + '\', \'' + title + '\')");">Bookmark this page</a>'); 
		} else if (window.opera && window.print) { // Opera Hotlist
			return document.write('<a rel="sidebar" href="' + url + '" title="' + title + '">Bookmark this page</a>');
		} 
	} catch(err) {
		// do nothing
	}
}

function createBookmarkLink(url, title) {
	try {
		if (window.sidebar) { // Mozilla Firefox Bookmark
			return window.sidebar.addPanel(title, url, "");
		} else if( window.external ) { // IE Favorite
			return window.external.AddFavorite( url, title); 
		} else if(window.opera && window.print) { // Opera Hotlist
			return true; 
		}
	} catch(err) {
		// do nothing
	}
}

function setHomepage(url)
{
 if (document.all)
    {
        document.body.style.behavior='url(#default#homepage)';
        document.body.setHomePage(url);
 
    }
    else if (window.sidebar)
    {
    	var error = false;
        if(window.netscape)
        {
             try
             {  
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
             }  
             catch(e)  
             {
            	 error = true;
            	 alert("Please set our web site as your home page\nthrough the preferences page of your web browser.");
             }
        } 
        if(!error) {
            var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch);
            prefs.setCharPref('browser.startup.homepage',url);
        }
    }
}


function visibleElement(current, all)
{
    
}

// *********  CWorldTime ***********************
function CWorldTime(divName){
    this.days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
    this.months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
	this.divName = divName;
	this.showTime = true;
	this.showDate = true;
	this.interval = 1000; // refresh time each second;
	this.localzone =0; //0=GMT, >0 west, <0 east
	this.timezone = ''; //
	this.delta = 0; // shift time in miliseconds from local time
	this.delta_server = 0; // shift time in miliseconds from server time
	this.AMPM = true; // show time in 12 or 24 hrs format
	this.IsDaylightSavingTime = false; // is daylight saving time now (summer) //not used now

	this.setTimezone = function(tz) {
		this.timezone = parseFloat(tz);
		this.delta = isNaN(this.timezone) ? 0 : (this.timezone - this.localzone) * 3600000;
	}
	
	this.stop = function() { var id=this.timerID; this.timerID = null; if(null!=id)window.clearTimeout(id);};
	this.start = function() {if(null!=this.timerID)stop(); var thisObj = this; this.tick();};
//	this.stop = function() { var id=this.timerID; this.timerID = null; if(null!=id)window.clearInterval(id);};
//	this.start = function() {if(null!=this.timerID)stop(); var thisObj = this; this.tick(); this.timerID = window.setInterval( function(){thisObj.tick();},this.interval);};
	this.tick = function() {
		var time = new Date();
		time.setTime(time.getTime()+this.delta + this.delta_server);
		this.display(time);
		var thisObj = this;
 		this.timerID = window.setTimeout(function(){thisObj.tick();},this.interval);
	}
	this.display = function(time){
	    var stime = '';
	    if(this.AMPM)
	    {
	        stime = (time.getHours()>12) ? 
	                   this.leaderzero(time.getHours()-12) + ':' + this.leaderzero( time.getMinutes() ) + ' PM' :
	                   this.leaderzero(time.getHours()) + ':' + this.leaderzero( time.getMinutes() ) + ' AM';
	    }
		else
		  stime = this.leaderzero(time.getHours()) + ':' + this.leaderzero( time.getMinutes() ) + ':' + this.leaderzero( time.getSeconds() );
		var sdate = this.months[time.getMonth()] + ' ' + time.getDate();
		var oTime = document.getElementById(this.divName);
		s = "";
		if(this.showTime) s += "<strong>"+stime+"</strong>";
		if(this.showDate && this.showTime) s +=", ";
		if(this.showDate) s += sdate;
		if(oTime) oTime.innerHTML = s;
	}
	this.leaderzero = function(n){return n<=9 ? '0'+n : n;}
	this.setDiff = function( server_time )
	{
	    var time = new Date();
	    this.delta_server = server_time*1000 - time.getTime();

	    
	}
	
	this.init = function(){
		var tz = new Date();
		//zonenow = tz.getTimezoneOffset()/60;
		this.localzone = -tz.getTimezoneOffset()/60;
		this.timezone = this.localzone;
		tz = new Date((new Date()).getFullYear(),0,1); //calculate localzone by winter time 
		winterzone = -tz.getTimezoneOffset()/60;
		this.IsDaylightSavingTime = (winterzone != this.localzone);
	}
	this.init();
	return this;
}

function preload_image (url) {
	var image = new Image();
	image.src = url;
}


/*
 * Date Format 1.2.2
 * (c) 2007-2008 Steven Levithan <stevenlevithan.com>
 * MIT license
 * Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */
var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date();
		if (isNaN(date)) throw new SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

// Return new array with duplicate values removed
Array.prototype.unique =
  function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };

//Window library helpers
var win;
var window_opened = false;

function createWindow(caption, wd, hg, link)
{
    if (!window_opened)
    {
        window_opened = true;
        win = new Window({className:"alphacube",
                              title: caption,
                              width: wd,
                              height: hg,
                              maximizable: false, minimizable: true, resizable: false,
                              url: link,
                              recenterAuto: true,
                              options: { method: "get" },
                              onClose: onCloseWindow,
                              destroyOnClose: true
                              });
        //win.setDestroyOnClose();
        win._center();
        win.show();
    }
}

function nAlert(text){
    var w = text.length + 200;
    Dialog.alert(text, {width: w, className:'alphacube'});
}

function onCloseWindow() {
    window_opened = false;
}


function createModalWindow(caption, wd, hg, link) {

    win = new Window({className:"alphacube",
                              title: caption,
                              width: wd,
                              height: hg,
                              maximizable: false, minimizable: false, resizable: false,
                              url: link,
                              recenterAuto: true,
                              options: { method: "get" },
                              onClose: onCloseWindow,
                              destroyOnClose: true
                              });

    win._center();
    win.show(true);
}

function createDialog(wd, hg, link)
{
    if (!window_opened)
    {
        window_opened = true;
        win = Dialog.alert( {url: link, options: {method: 'get'}},
                   {windowParameters:
                        {className: "alphacube", width:wd, height:hg, 
                        hasButton: false, destroyOnClose: true, closable: true, onClose: onCloseWindow}
                   });
    }
}

function createConfirm(url, content, _callback)
{
    if (!window_opened)
    {
        window_opened = true;
        win = Dialog.confirm ( content,
                        {width:250,
                         className: "alphacube",
                         destroyOnClose: true,
                         okLabel: "Yes",
                         cancelLabel:"No",
                         onClose: onCloseWindow,
                         onCancel: function(){ return false },
                         onOk: function()
                               {
                                    if (!url.match('#'))
                                        window.location.href = url;
                                    else {
                                        if (_callback) {
                                            _callback();
                                        }
                                        return true;
                                    }
                                },
                         options: {parent: null}}
        );
    }
}

/*
objSort v 1.1
copyright 2006 Thomas Frank

This program is free software under the terms of the
GNU General Public License version 2 as published by the Free
Software Foundation. It is distributed without any warranty.
*/

tfObjSort={
	init:function(){
		Array.prototype.objSort=function(){
			tfObjSort.setThings(this);
			var a=arguments;
			var x=tfObjSort;
			x.a=[];x.d=[];
			for(var i=0;i<a.length;i++){
				if(typeof a[i]=="string"){x.a.push(a[i]);x.d.push(1)};
				if(a[i]===-1){x.d[x.d.length-1]=-1}
			}
			return this.sort(tfObjSort.sorter);
		};
		Array.prototype.strSort=function(){
			tfObjSort.setThings(this);
			return this.sort(tfObjSort.charSorter)
		}
	},
	sorter:function(x,y){
		var a=tfObjSort.a
		var d=tfObjSort.d
		var r=0
		for(var i=0;i<a.length;i++){
			if(typeof x+typeof y!="objectobject"){return typeof x=="object"?-1:1};
			var m=x[a[i]]; var n=y[a[i]];
			var t=typeof m+typeof n;
			if(t=="booleanboolean"){m*=-1;n*=-1}
			else if(t.split("string").join("").split("number").join("")!=""){continue};
			r=m-n;
			if(isNaN(r)){r=tfObjSort.charSorter(m,n)};
			if(r!=0){return r*d[i]}
		}
		return r
	},
	charSorter:function(x,y){
		if(tfObjSort.ignoreCase){x=x.toLowerCase();y=y.toLowerCase()};
		var s=tfObjSort.chars;
		if(!s){return x>y?1:x<y?-1:0};
		x=x.split("");y=y.split("");l=x.length>y.length?y.length:x.length;
		var p=0;
		for(var i=0;i<l;i++){
			p=s.indexOf(x[i])-s.indexOf(y[i]);
			if(p!=0){break};
		};
		if(p==0){p=x.length-y.length};
		return p
	},
	setThings:function(x){
		this.ignoreCase=x.sortIgnoreCase;
		var s=x.sortCharOrder;
		if(!s){this.chars=false;return true};
		if(!s.sort){s=s.split(",")};
		var a="";
		for(var i=1;i<1024;i++){a+=String.fromCharCode(i)};
		for(var i=0;i<s.length;i++){
			z=s[i].split("");
			var m=z[0]; var n=z[1]; var o="";
			if(z[2]=="_"){o=n+m} else {o=m+n};
			a=a.split(m).join("").split(n).join(o);
		};
		this.chars=a
	}
};
tfObjSort.init();

function conferenceMessagesChecker()
{
    $j.post('/ConferenceRoom/checkChat',
            {},
            function(data, textStatus){                
                try {
                    if (textStatus == 'success')
                        if (data.session_expired){
                            window.location.reload();
                        } else {
                            new_conference_messages( data.conference_messages );
                        }
                } catch(err){}
            },
            'json');


    
}

var conference_blinker = [];

function isSoundOn(){
    s_button = $('chat_sound_button');
    if (s_button.className == 'sound-on'){
        return true;
    } else {
        return false;
    }
}

function new_conference_messages( messages ) {
    if (messages.length > 0 /*&& document.location.href.indexOf('ConferenceRoom') == -1*/) {
        if (isSoundOn()){
            if ($j.browser.msie || soundManager == undefined || !soundManager.supported()){
                Sound.play('/sound/2.wav');
            }else{
                soundManager.play('conf_room_msg_in');
            }
        }
        for (var mn=0; mn < messages.length; mn++) {
                $('bigConferenceButton').href = '/main/ConferenceRoom/' + messages[mn].room_id;

                if (!conference_blinker[messages[mn].room_id]) {
		    var message = messages[mn];
                    conference_blinker[message.room_id] = new PeriodicalExecuter(function(pe)
                    {
                        if ( !$('bigConferenceButton').hasClassName('hover') ) {
                            document.title = 'New Group Chat in "'+ message.name + '" Conference Room';
                            $('bigConferenceButton').addClassName('hover');
                        } else {
                            document.title = '5050Biz';
                            $('bigConferenceButton').removeClassName('hover');
                        }
                    }, 3);
	        }
            
        }
    }
}








if (typeof($j) != 'undefined') {
    $j(document).ready(
        function(){

            $j('div.notice-item div.notice-item-close').click(function(){
                $j(this).parent().fadeOut();
            });

            if ($j('div.notice-item').get(0)) {
                $j('div.notice-item').fadeIn(700, function(){
                            setTimeout(function(){
                                $j('div.notice-item').filter(':visible').fadeOut();
                            }, 5000);
                        });
            }
        }
    );
}