var locale = new Object();
locale.write = 'Написать сообщение';
locale.reply = 'Ваш ответ';
locale.view_photo = 'Посмотреть фото';
locale.gallery = 'Посмотреть галлерею';
locale.friends = 'Друзья';
locale.guestbook = 'Гостевая книга';
locale.messages = 'Архив сообщений';
locale.gifts = 'Подарить';
locale.remove = 'Удалить друга';
locale.add = 'Invite to friends';
locale.change_status = 'Статус друга';
locale.notify_tab = 'Notify\'s';
locale.send = 'Отправить';
locale.close = 'Закрыть';
locale.new_messages = 'Сообщения (%s)';
locale.profile = 'Мой профиль';
locale.complain = 'File a complaint';
locale.flash_new_message = '* Новое сообщение *';
locale.view_profile = 'Смотреть профиль';
locale.open_chat = 'Открыть ЧаТ';
locale.addremove_friend = 'Добавить / Удалить друга';
locale.blogs = 'Блог';

locale.photo_edit_com = 'Редактировать комментарий';
locale.photo_move_to = 'Перенести фото';
locale.photo_set_default = 'Сделать главной';
locale.photo_delete = 'Удалить фото';

locale.complain_select_reasoin = 'Пожалуйста, укажите причину.';
locale.complain_fill_reasoin = 'Пожалуйста, опишите причину.';

locale.friends_recently = 'Recently added';
locale.friends_all = 'Все друзья';
locale.friends_invite = 'Пригласить друзей';
locale.friends_find = 'Найти друзей';
locale.new_sys_notty = '*Новое оповещение*';
locale.new_chat_notty = '*Новое сообщение*';

var calendar = {
	months : [ 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь' ],
	days : [ 'Воскресение', 'Понидельник', 'Вторник', 'Среда', 'Четверг', 'Пятница','Суббота' ]
};

var currentX = -1;
var currentY = -1;

var leftmenuTimer = null;

var menuTimer = null;
var showPhoneBlock = 0;
var phoneTimer = null;
var showMenuBlock = 0;
var friendMenuBlock = 0;
var friendMenuTimer = null;

var isMsie = false;
var isMozilla = false;
var isOpera = false;
var isSafari = false;
var lastMsgId = '';
var messagePoll = new Array();
var init = false;
var title = null;
var profile = null;
var informer = null;
var user = null;
var message = null;
var active = false;
var flashing_timer = null;
var the_title = window.document.title;

var smile_path = '/skins/smiles/'
var smiles = new Array();
smiles[':)'] =	'-1px';
smiles[';)'] =	'-18px';
smiles[':P'] =	'-36px';
smiles[':]'] =	'-54px';
smiles[':D'] =	'-72px';
smiles['8}'] =	'-90px';
smiles[':`('] = '-108px';
smiles[':`)'] = '-162px';
smiles[':('] =	'-126px';
smiles['=0'] =	'-144px';
smiles['(h)'] = '-180px';
smiles['(k)'] = '-198px';
smiles['(c)'] = '-216px';
smiles['(f)'] = '-234px';


var flash_timer     = null;
var sys_title_data = new Array(locale.new_sys_notty, '*Multimania.tv*', window.document.title);
var chat_title_data = new Array(locale.new_chat_notty, '*Multimania.tv*', window.document.title);
var title_index = 0;

var sys_notifier_active = false;
var chat_notifier_active = false;


var my_array = 0;
var glob_id = 0;
/**
 * Detect current browser and set mouse handler
 */
function detectBrowsers() {
	jQuery.each(jQuery.browser, function(i, val) {
		if (i.toLowerCase() != "version" && val) {
			var name = i.charAt(0).toUpperCase() + i.substr(1);
			eval('is' + name + ' = true;');
		}
	});
	document.onmousemove = trackMouse;
}

/**
 * Mouse movement tracking handler
 */
function trackMouse(e) {
	var x = 0;
	var y = 0;
	if (isMsie) {
		// must be IE
		try {
			x = event.clientX + document.documentElement.scrollLeft;
			y = event.clientY + document.documentElement.scrollTop;
		} catch (e) {
		}
	} else {
		try {
			x = e.pageX;
			y = e.pageY;
		} catch (e) {
		}
	}
	currentX = (x < 0 ? 0 : x);
	currentY = (y < 0 ? 0 : y);
}

function showPhoto(pht_id, x, y) {
	menuTimer = setTimeout('showPhotoMenu(' + pht_id + ',' + x + ',' + y +');', 500);
}

function hidePhoto() {
	if (menuTimer) {
		clearTimeout(menuTimer);
		menuTimer = null;
	}
	if (showMenuBlock == 1) {
		showMenuBlock = 0;
		setTimeout('hidePhotoMenu()', 500);
	}
}



/**
 * Set timer for context menu hiding. Timer is needed because moving mouse over
 * context menu itself generates onmouseout within the image itself
 */
function hideMenu() {
	if (menuTimer) {
		clearTimeout(menuTimer);
		menuTimer = null;
	}
	if (showMenuBlock == 1) {
		showMenuBlock = 0;
		setTimeout('hideContextMenu()', 500);
	}
}

/**
 * Drop menu before AJAX CALL
 *
 * @return
 */
function dropMenu() {
	if (menuTimer) {
		clearTimeout(menuTimer);
		menuTimer = null;
	}
	if (showMenuBlock == 1) {
		showMenuBlock = 0;
		hideContextMenu();
	}
}

/**
 * Hide block after timeout if hide flag is 0
 */
function hideContextMenu() {
	if (showMenuBlock == 0) {
		//$('#contextmenu').fadeout('slow', function() {
			obj = document.getElementById('contextmenu');
			obj.innerHTML = '';
			obj.style.left = '-500px';
			obj.style.top = '-500px';
		//});

	}


}

/**
 * Calculate block drawing position taking into account browser window borders
 */
function calculatePosition(id) {
	var tabW = document.getElementById(id).offsetWidth;
	var tabH = document.getElementById(id).offsetHeight;

	if (window.innerWidth) {
		var winW = window.innerWidth;
		var winH = window.innerHeight;
	} else if (document.documentElement && document.documentElement.clientWidth) {
		var winW = document.documentElement.clientWidth;
		var winH = document.documentElement.clientHeight;
	} else if (document.body) {
		var winW = document.body.clientWidth;
		var winH = document.body.clientHeight;
	}

	if (window.pageYOffset) {
		var scrT = window.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {
		var scrT = document.documentElement.scrollTop;
	} else if (document.body) {
		var scrT = document.body.scrollTop;
	}

	if (currentX > winW - tabW) {
		currentX = winW - tabW - 25;
	} else {
		currentX = currentX + 5;
	}

	if ((currentY - scrT) > (winH - tabH)) {
		currentY = scrT + winH - tabH - 5;
	} else {
		currentY = currentY + 10;
	}
}

/**
 * Write HTML to specified element and show it near the mouse pointer
 */
function displayBlock(html, id, x, y, gm, beginning) {
	if (typeof x == "undefined") {
		x = 0;
	}
	if (typeof y == "undefined") {
		y = 0;
	}
	if (typeof gm == "undefined") {
		gm = 0;
	}
	if (typeof beginning == "undefined") {
		beginning = 0;
	}

	var obj = document.getElementById(id);
	obj.innerHTML = html;
	calculatePosition(id);
	if (gm > 0) {
		while(currentX + x + 520 > window.innerWidth) {
			x = x - 10;
		}
	}
	if (beginning > 0) {
		obj.style.left = x + 'px';
		obj.style.top = y+120 + 'px';
	} else {
		obj.style.left = (currentX + x) + 'px';
		obj.style.top = (currentY + y) + 'px';
	}
	showMenuBlock = 1;
	showPhotoBlock = 1;
	showPhoneBlock = 1;

	$.AjaxCall();

}

/**
 * Load specified url in current window/tab
 */
function goTo(url, opener) {
	if (typeof opener != "undefined") {
		window.opener.location.href = url;
	} else {
		window.location.href = url;
	}
}

/**
 * Show and hide element
 *
 */
function showHideIt(id) {
	var obj = document.getElementById(id);
	obj.style.display = (obj.style.display == "none") ? "" : "none";
	return false;
}

/**
 * Check radio button, according to selected vote mark
 */
function AddMark(obj) {
	obj.parentNode.getElementsByTagName('input')[0].checked = "checked";
	return false;
}

/**
 * Uncheck all checkboxes under specified name
 */
function uncheck(name) {
	var el = document.getElementsByName(name);
	for ( var i = 0; i < el.length; ++i) {
		el[i].checked = false;
	}
}

function getSmiles(split) {
	return '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=":)" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -1px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=";)" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -18px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=":P" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -36px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=":]" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -54px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=":D" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -72px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title="8}" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -90px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=":`(" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -108px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ (typeof split != "undefine" && split ? '<br \/>' : '')
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=":`)" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -162px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title=":(" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -126px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title="=0" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -144px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title="(h)" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -180px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title="(k)" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -198px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title="(c)" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -216px 0px;" height="18" hspace="2" vspace="1" width="18" \/>'
			+ '<img onclick="write_smile(this); return false;" src="/skins/_.png" title="(f)" style="cursor: pointer; background: url(\'/skins/smiles/smiles.png\') -234px 0px;" height="18" hspace="2" vspace="1" width="18" \/>';
}






/**
 * Let user to enter only numbers to text field
 */
function testKey(e) {
	// Make sure to use event.charCode if available
	var key = (typeof e.charCode == 'undefined' ? e.keyCode : e.charCode);

	// Ignore special keys
	if (e.ctrlKey || e.altKey || key < 32)
		return true;

	key = String.fromCharCode(key);
	return /\d/.test(key);
}

/**
 * Forward page according to pager data
 */
function goToPage(o, url, appurl) {
	var page = parseInt(o.page.value);

	if (appurl == "undefined") {
		appurl = '';
	}

	if (page) {
		var link = $(o).find('a');
		link.attr('href', url + page + appurl);
		link.click();
		return false;
	}

	return false;
}

/**
 * Check if username or e-mail exists at DB
 *
 */
function checkUserSignup(obj, type) {

	return;

	var value = obj.value;
	if (value.length) {
		var send = type.replace('signup-', '');
		$.get('/ajax/signup/checkUser/' + send + '/' + value + '.html', {},
				function(resp) {
					if (resp == '1') {
						showUserSignupError(send);
					} else {
						hideUserSignupError(send);
					}
				});
	}
	return;
}

/**
 * Show error at signup form
 *
 */
function showUserSignupError(type) {
	var error = 'Этот ' + ((type == 'username') ? 'username' : 'e-mail');
	var cell = $('#signup-' + type);
	cell.html('<span class="error">' + error + ' уже существует<br /></span>');
}

/**
 * Hide error at signup form if user changed username or e-mail
 *
 */
function hideUserSignupError(type) {
	var error = 'Этот ' + ((type == 'username') ? 'username' : 'e-mail');
	var cell = $('#signup-' + type);
	cell.empty();
}

function clearFlashingTimer() {
	clearTimeout(flashing_timer);
	flashing_timer = null;
}

function flashTitle(start) {
	if (start && active) {
		if (flashing_timer != null) {
			clearFlashingTimer();
		}
		flashing_timer = setTimeout('doFlashing(true)', 1000);
	} else {
		clearFlashingTimer();
		window.document.title = the_title;
	}
}

function doFlashing(action) {
	window.document.title = action ? locale.flash_new_message : the_title;
	flashing_timer = setTimeout('doFlashing(' + !action + ')', 1000);
}

function write_smile(obj) {
	var $text = $('#msg_editor').val() + obj.title + ' ';
	$('#msg_editor').val($text).focus();
}

function parseSmiles(msg) {
	var result = msg;
	for (smile in smiles) {
		if (result != null && result.length > 0) {
			var a = 0;
			var b = 0;
			var aReplace = '<img src="/skins/_.png" ' +
					'" class="smile" height="18" width="18" alt="' + smile + '"' +
					' align="baseline" '+
					'style="background: url(\'/skins/smiles/smiles.png\') '+smiles[smile]+' 0px;">';
			while (true) {
				a = result.indexOf(smile, b);
				if (a != -1) {
					result = result.substring(0, a) + aReplace
							+ result.substring(a + smile.length);
					b = a + aReplace.length;
				} else
					break;
			}
		}
	}
	return result;
}

$.ui.dialog.prototype._createButtons = function(buttons) {
	var self = this, hasButtons = false, uiDialogButtonPane = $('<div></div>').addClass('ui-dialog-buttonpane ' + 'ui-widget-content ' + 'ui-helper-clearfix');

	// if we already have a button pane, remove it
	this.uiDialog.find('.ui-dialog-buttonpane').remove();

	(typeof buttons == 'object' && buttons !== null && $.each(buttons,
			function() {
				return !(hasButtons = true);
			}));
	if (hasButtons) {
		$.each(buttons, function(name, fn) {
			$('<span></span>').addClass('input-button').html(
					$('<span></span>').text(name).append($('<input type="button" />').click(function() {
								fn.apply(self.element[0], arguments);
							}))).appendTo(uiDialogButtonPane);
		});
		uiDialogButtonPane.appendTo(this.uiDialog);
	}
}


/**
 * Get list of countries, cities, regions
 *
 */

jQuery.getCountries = function(id, def_country, do_next_select) {

	if (typeof def_country == "undefined" || def_country.length == 0) {
       	def_country = '';
	}

	$.getJSON("/ajax/location/getCountries/"+def_country, function(data) {

		var country = $('#' + id);

		country.attr("disabled", true);
		country.empty();
            country.append('<option value="">Выберите страну</option>');
		$.each(data, function(i, item) {
			country.append('<option value="' + item.id + '" '
					+ ((item.st == 1) ? 'selected="selected"' : '') + '>'
					+ item.name + '</option>');
			if (item.st == 1) {
				def_country = item.id;
			}
		});

		if (country.html() != null) {
			country.attr("disabled", false);
			if (typeof do_next_select == "undefined" || do_next_select){
				$.getRegions('select-region', country.val());
			}
		}
	})
};

jQuery.getRegions = function(id, country_id, def_region, do_next_select) {

	if (typeof def_region == "undefined") {
		def_region = '';
	}

	var region = $('#' + id);
	region.empty();
	region.attr("disabled", true);

	var url = "/ajax/location/getRegions/" + country_id + '/' + def_region;
	$.getJSON(url, function(data) {
		if (data.length > 0) {
			region.append('<option value="">Выберите регион</option>');
			$.each(data, function(i, item) {
				region.append('<option value="' + item.id + '" ' +
					((item.id == def_region) ? 'selected="selected"' : '') + '>'
					+ item.name + '</option>');
			});
			if (region.html() != null && region.html().length > 0) {
				region.attr("disabled", false);
			}
			if (region.val() != '' && do_next_select == true) {
				$.getCities('select-city', $('#select-country').val(), region.val());
			} else {
				$('#select-city').empty();
				$('#select-city').attr("disabled", true);
			}
		} else {

			region.empty();
			region.append('<option value="">Регионы не найдены</option>');

			if (typeof do_next_select == "undefined" || do_next_select) {
				$.getCities('select-city', $('#select-country').val());
			}

		}
	})
};

jQuery.getCities = function(id, country_id, reg_id, def_city, direction) {
	if (typeof reg_id == "undefined" || reg_id.length == 0) {
		reg_id = '';
	}

	var url = "/ajax/location/getCities/" + country_id + "/" + reg_id + "/" + def_city;
	$.getJSON(url, function(data) {

		var city = $('#' + id);

		city.attr("disabled", true);
		city.empty();

		city.append('<option value="">Выберите город</option>');
		$.each(data, function(i, item) {
			city.append('<option value="' + item.id + '"' +
				((item.id == def_city) ? ' selected="selected"' : '') + '>' +
				item.name + '</option>');
		});
		if (city.html().length > 0) {
			city.attr("disabled", false);
		} else {
			city.empty();
			city.append('<option value="">Города не были найдены</option>');
		}
	})
};

jQuery.getSatellite = function(id, country_id, reg_id, city_id, def_sat, direction) {
	if (typeof reg_id == "undefined" || reg_id.length == 0) {
		reg_id = '';
	}
	if (typeof city_id == "undefined" || city_id.length == 0) {
		city_id = '';
	}
	var url = "/ajax/location/getSatellite/" + country_id + "/" + reg_id + "/" + city_id + "/" + def_sat;
	$.getJSON(url, function(data) {

		var satellite = $('#' + id);

		//satellite.attr("disabled", true);
		satellite.empty();
		$.each(data, function(i, item) {
			satellite.append('<div style="text-align:center;font-size:14px;font-weight:bold;color:#b1211d;">Информация по Вашему запросу</div>' +
			
				'<div style="text-align:justify;padding-top:20px;">' +item.name + '</div>');
		});
			if (satellite.html().length <= 0) {
		
			satellite.empty();
			satellite.append('<div style="text-align:center;color:red;font-size:14px;">Нет данных</div>');
			}

		
		
	})
};
jQuery.DoSearch = function(id,Srchword) {
	if (typeof Srchword == "undefined" || Srchword.length == 0) {
		Srchword = '';
	}

	var url = "/ajax/programm/ProgrammQuickSearch/" + Srchword + ".html";
	$.getJSON(url, function(data) {

		var Srchresult = $('#' + id);

		//satellite.attr("disabled", true);
		Srchresult.empty();
		$.each(data, function(i, item) {
			Srchresult.append('<div style="text-align:center;font-size:14px;font-weight:bold;color:#b1211d;">Информация по Вашему запросу</div>' +
			
				'<div style="text-align:justify;padding-top:20px;">' +item.name + '</div>');
		});
			if (Srchresult.html().length <= 0) {
		
			Srchresult.empty();
			Srchresult.append('<div style="text-align:center;color:red;font-size:14px;">Нет данных</div>');
			}

		
		
	})
};
jQuery.getSchools = function(id, direction, reg_id, city_id, def_school) {

	if (typeof city_id == "undefined" || city_id.length == 0) {
		city_id = '455313';
	}

	if (typeof reg_id == "undefined" || reg_id.length == 0) {
		reg_id = '455313';
	} else {
		reg_id = reg_id;
	}

	var url = "/ajax/schools/"+direction+"/" + reg_id + "/" + city_id;
	$.getJSON(url, function(data) {

		var schools = $('#' + id);

		schools.attr("disabled", true);
		schools.empty();

		schools.append('<option value="">Выбор</option>');
		$.each(data, function(i, item) {
			schools.append('<option value="' + item.sch_id  + '"'+
					((item.sch_id == def_school) ? ' selected="selected"' : '') + '>' +
					item.sch_name + '</option>');
		});
		if (schools.html().length > 0) {
			schools.attr("disabled", false);
		} else {
			schools.empty();
			schools.append('<option value="">Школы не были найдены</option>');
		}
	})
};

jQuery.getSections = function(id, sch_id, def_section) {

	if (typeof sch_id == "undefined" || sch_id.length == 0) {
		sch_id = '';
	}

	var url = "/ajax/schools/sections/" + sch_id;
	$.getJSON(url, function(data) {

		var section = $('#' + id);

		section.attr("disabled", true);
		section.empty();
		section.append('<option value="">Выбор</option>');
		$.each(data, function(i, item) {
			section.append('<option value="' + item.sct_id + '"' +
					((item.sct_id == def_section) ? ' selected="selected"' : '') + '>' +
					item.sct_name + '</option>');
		});
		if (section.html().length > 0) {
			section.attr("disabled", false);
		} else {
			section.empty();
			section.append('<option value="">Не найдено</option>');
		}

	})
};


function currDate(timestamp, places) {
	var timer_dt = new Date();
	timer_dt.setTime(timestamp);

	var week_day = calendar.days[timer_dt.getDay()];
	var day = addZero(timer_dt.getDate());
	var month = calendar.months[timer_dt.getMonth()];
	var year = timer_dt.getFullYear();
	var hours = addZero(timer_dt.getHours());
	var minutes = addZero(timer_dt.getMinutes());
	var seconds = addZero(timer_dt.getSeconds());


	for (i=0; i < places.length; i++) {

		if (places[i] == "top") {
			var curr_date = week_day + ', ' + day + ' ' + month + ' ' + year + ' - '+ hours + ":" + minutes;
			$('#head-date').html(curr_date);
		} else if (places[i] == "blogs") {
			if ($('#blog-date').length) {
				var curr_date = day + ' ' + month + ' ' + year + ' - ' + hours + ':' + minutes;
				$('#blog-date').html(curr_date);
			}
		}

	}



	if (typeof additional != "undefined") {
		for (i = 0; i < length(additional); i++) {

		}
	}

	var new_timestamp = ((timestamp / 1000) + 60) * 1000;
	setTimeout(function() {
		currDate(new_timestamp, places);
	}, 60000);
}

function addZero(num) {
	if (num < 10) {
		num = '0' + num;
	}
	return num;
}

function str_split ( f_string, f_split_length){
    f_string += '';

    if (f_split_length == undefined) {
        f_split_length = 1;
    }
    if (f_split_length > 0) {
        var result = [];
        while (f_string.length > f_split_length) {
            result[result.length] = f_string.substring(0, f_split_length);
            f_string = f_string.substring(f_split_length);
        }
        result[result.length] = f_string;
        return result;
    }
    return false;
}

function in_array (needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        if (typeof(needle)=='string') {
            str = haystack.toString();
            return (str.search(needle) !== false);
        }

        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

function array_unique(array,numeric){
    var tem_arr = new Array();
    for(i=0;i < array.length;i++){
        if(numeric === true && typeof(array[i]) == 'string' && !isNaN(array[i])) {
        	array[i]=parseInt(array[i], 10);
        }
	    if(tem_arr.length == 0){
	        tem_arr[i] = array[i];
	    } else {
	    	var exist = false;
	        for(var j=0; j<tem_arr.length; j++){
	            if(tem_arr[j] === array[i]){
	                exist = true;
	            }
	        }
	        if(!exist){
	            if(array[i] != null){
	                tem_arr[i] = array[i];
	            }
			}
	    }
    }
    return tem_arr.join(' ').replace(/\s{2,}/g,' ').split(' ');
}

function test_password($password)
{
    if ($password.length == 0 )
    {
        return 0;
    }

    var $strength = 0;

    var $length = $password.length;

    /*** check if password is not all lower case ***/
    if($password.toLowerCase() != $password)
    {
        $strength += 5;
    }

    /*** check if password is not all upper case ***/
    if($password.toUpperCase() == $password)
    {
        $strength += 5;
    }

    /*** check string length is 8 - 10 chars ***/
    if($length >= 6 && $length <= 8)
    {
        $strength += 5;
    }

    /*** check if lenth is 10 - 15 chars ***/
    if($length >= 9 && $length <= 12)
    {
        $strength += 15;
    }

    /*** check if length greater than 15 chars ***/
    if($length > 12)
    {
        $strength += 20;
    }

    /*** get the numbers in the password ***/
    var $tmp = $password.match(/[0-9]+/);
    if (typeof $tmp == 'string') {
    	$strength += $tmp.length;
    }

    /*** check for special chars ***/
    var $tmp = $password.match(/[|!@#$%&*\/=?,;.:\-_+~^\\]+/);
    if (typeof $tmp == 'string') {
    	$strength += $tmp.length;
    }
    /*** get the number of unique chars ***/
    var $chars = str_split($password);
    var $num_unique_chars = array_unique($chars).length;
    $strength += $num_unique_chars * 3;
    /*** strength is a number 1-10; ***/
    $strength = $strength > 99 ? 99 : $strength;
    $strength = Math.floor($strength / 10 + 1);

    return $strength;
}

/* show flashing title about new notification */
function flash_title(id, action){
	if ((typeof id == 'undefined' && flash_timer == null) ||
		(typeof id != 'undefined' && id == 1)) {

		if (action == 'chat' && !sys_notifier_active) {
			var title = chat_title_data;
			chat_notifier_active = true;

		} else {
			var title = sys_title_data;
			sys_notifier_active = true;
		}

        window.document.title = title[title_index];
        title_index++

		if ((title_index+1) >= title.length) {
			title_index = 0;
		}
		flash_timer = setTimeout(function(){flash_title(1,action)}, 1000);
	}
}

/* switch off flashing title */
function close_flash_title(action){
	if (flash_timer != null){

		title_index = 0;

		if (action == 'chat' && !sys_notifier_active) {
			var title = chat_title_data;
			chat_notifier_active = false;

		} else {
			var title = sys_title_data;
			sys_notifier_active = false;
		}


		clearTimeout(flash_timer);
		flash_timer = null;
		window.document.title = title[2];
	}
}


//================================================================================================================================================







jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
