/*<script type="javascript">*/var consoleDebug = 0;

function OnReady(){
	$("#mainMenu > ul > li").click(function(){
		var hasClass = $(this).hasClass('click');
		$("#mainMenu > ul > li").removeClass('click');
		if(!hasClass){ $(this).addClass('click'); }
	});
	$("#mainMenu > ul > li > a:nth-child(1)").click(function(e){
	    e.preventDefault();
	});
	$(document).click(function(e){
    	var parents = $(e.target).parents();
		var inMenu = false;
		for(var i = 0; i < parents.length; ++i){
			if($(parents[i]).attr('id') == 'mainMenu'){
				inMenu = true;
			}
		}
		if(!inMenu){ $("#mainMenu > ul > li").removeClass('click'); }
	});
	
	var i;
		var formIDStatus = 0; 
	if(
		typeof(document.form) == "object" && 
		typeof(document.form.back) == "object" && 
		typeof(document.form.formID) == "object"
	){
		var submittedFormIDs = GetCookie('submittedFormIDs') ? GetCookie('submittedFormIDs') : '';
		submittedFormIDs = submittedFormIDs.length ? submittedFormIDs.split(',') : [];
		for(i in submittedFormIDs){ if(submittedFormIDs[i] == document.form.formID.value){ formIDStatus = 1; break; }}
		var processedFormIDs = GetCookie('processedFormIDs') ? GetCookie('processedFormIDs') : '';
		processedFormIDs = processedFormIDs.length ? processedFormIDs.split(',') : [];
		for(i in processedFormIDs){ if(processedFormIDs[i] == document.form.formID.value){ formIDStatus = 2; break; }}
		if(formIDStatus == 1 || formIDStatus == 2){
			var inputs = document.form.getElementsByTagName('input');
			for(i = 0; i < inputs.length; ++i){ if(inputs[i].type == 'submit'){ inputs[i].disabled = (formIDStatus == 1 ? false : true); }}
		}
	}
	 
	ChangeCaptcha();
		if(typeof(Images.initialFormImages) != "undefined"){
		Images.ShowFormImages();
		Images.Preload('/images/uploading.gif');
	}
		Images.WriteItemSlides(false);
	
		ItemsToggle('show', 'item', window.showItems.ads, 1);
	ItemsToggle('show', 'fr', window.showItems.frs, 1);
	
		$('.activeNode').each(function(index) {
		window.location = $(this).attr('href');
	});
	
	Popup.Init();
	Forms.Init();
	Stream.Init();

}

var repeatCaptcha = 1;
function ChangeCaptcha(){
	if(repeatCaptcha++ > 3){ alert(".عفواً.. لا يمكنك تغيير الصورة أكثر من ثلاث مرات"); }
	else if(document.images['imgCaptcha']){ document.images['imgCaptcha'].src = '/captcha.php?i=' + Math.random(); }
}

function ChangeColor(field, value, css){
	if(field.value == value){ field.className = "color gWhite " + css; }else{ field.className = "color gH3 " + css; }
}

function ArraySum(a){
	var s = 0;
	for (var i = 0; i < this.length; i++){
		s += (typeof(this[i]) == 'number') ? this[i] : 0;
	}
	return s;
}

function Brands(b, m, type, brand, noFirstOption){
	if(Utils.ArrayIndexOf(["41","42","43","46","61"], type) != -1){
		var section;
		if(type == "61"){
			section = 6;
			document.getElementById('models').style.display = "none";
			m.disabled = true;
		}else{
			section = 4; 
			document.getElementById('models').style.display = "inline";
			m.disabled = false;
		}
		document.getElementById('brands').style.display = "inline";
		b.disabled = false; 		if(noFirstOption){
			j = 0;
			b.length = 0; 			b.length = parseInt(BL[section]);
		}else{
			j = 1;
			b.length = 1; 			b.length = parseInt(BL[section]) + 1;
			b.options[0].style.backgroundColor = "white";
		}
		for(i = 0; i < BL[section]; i++){
			b.options[j].value = BO[section][i];
			b.options[j].text = B[section][BO[section][i]];
			if(BO[section][i] == brand){ b.options[j].selected = 1; }
			j++;
		}
	}else{
		document.getElementById('brands').style.display = "none";
		document.getElementById('models').style.display = "none";
		b.disabled = true;
		m.disabled = true;
	}
	if(document.getElementById("tHint")){
		if(type == 0){ document.getElementById("tHint").innerHTML = "اختر قسم الإعلان."; }
		else{ if(TD[type]){ document.getElementById("tHint").innerHTML = TD[type]; }else{ document.getElementById("tHint").innerHTML = "كل إعلانات الأقسام الفرعية لهذا القسم"; } }
	}
}

function LocationDes(location){
	if(LD[location]){ document.getElementById("lHint").innerHTML = LD[location]; }
	else{ document.getElementById("lHint").innerHTML = "اختر مكان الإعلان."; }
}

function BidStatus(value){
	if(value == 2){ document.form.bidStart.disabled = false; document.form.bidCurrency.disabled = false; }
	else{ document.form.bidStart.disabled = true; document.form.bidCurrency.disabled = true; }
}

function PayableServicesSpecial(){
	if(isNaN(document.form.period.value)){ document.form.amount.value = 0; }
	else{
		document.form.amount.value = document.form.period.value * 35;
		if(document.form.amount.value > 350){ document.form.amount.value = 350; }
	}
}

function PayableServicesFixed(){
	if(document.form.type.value == "1. الإعلانات المثبتة في الصفحة الرئيسية"){ week = 250; month = 800; }
	else if(document.form.type.value == "2. الإعلانات المثبتة في أقسام السوق"){ week = 150; month = 500; }
	else{ week = 0; month = 0; }
	if(document.form.period.value == "أسبوع"){ document.form.amount.value = week; }
	else if(document.form.period.value == "أسبوعين"){ document.form.amount.value = 2 * week; }
	else{ document.form.amount.value = document.form.period.value * month; }
}

function PayableServicesBrokerCalculate(isTotal, amount){
		return isTotal ? 
			{"toSeller"	:Math.round(amount * 0.97), "toMstaml":amount - Math.round(amount * 0.97)} : 
			{"total"	:Math.round(amount / 0.97), "toMstaml":Math.round(amount / 0.97) - amount};
}

function PayableServicesBroker(i){
	if(i){
		if(parseInt(document.form.amount.value) && parseInt(document.form.amount.value) > 29){
			var amounts = PayableServicesBrokerCalculate(true, parseInt(document.form.amount.value));
			document.form.amountToSeller.value = amounts.toSeller;
			document.form.amountToMstaml.value = amounts.toMstaml;
			if(amounts.toMstaml < 30){
				document.form.amountToMstaml.value = 30;
				document.form.amountToSeller.value = parseInt(document.form.amount.value) - 30;
			}
		}else{
			document.form.amountToSeller.value = '';
			document.form.amountToMstaml.value = '';
		}
	}else{
		if(parseInt(document.form.amountToSeller.value) && parseInt(document.form.amountToSeller.value) > 0){
			var amounts = PayableServicesBrokerCalculate(false, parseInt(document.form.amountToSeller.value));
			document.form.amount.value = amounts.total;
			document.form.amountToMstaml.value = amounts.toMstaml;
			if(amounts.toMstaml < 30){
				document.form.amountToMstaml.value = 30;
				document.form.amount.value = parseInt(document.form.amountToSeller.value) + 30; // *1 is imp to be adding numbers not concatenating strings
			}
		}else{
			document.form.amount.value = '';
			document.form.amountToMstaml.value = '';
		}
	}
}

function PayableServicesCommission(){
	if(isNaN(document.calculateCommission.total.value)){
		document.calculateCommission.commission.value = "X";
		alert(".يرجى إضافة أرقام فقط");
	}else{ document.calculateCommission.commission.value = Math.round(document.calculateCommission.total.value) / 100; }
}

var threads = new Object();
function ThreadEdit(id, move){
	document.form.body.value = threads['ID' + id];
	document.form.thr.value = id;
	document.form.edit.style.visibility = "visible"
	if(move){ window.location = String(window.location).replace(/\#.*$/, "") + "#thread"; }
}

var userInfo = new Object();
function ShowUserInfo(info){
	var domainRegExp = "^.*\\." + "mstaml.com".replace(".", "\\.") + "$";			
	if(window.location.host.match(domainRegExp)){
		document.write(info);
	}else{
		document.write("<a href='http://www.mstaml.com'>هذا المعلومات مسروقة من موقع مستعمل</a>");
	}
}

function SetCookie(name, value, expire){
	var expireStr = '';
	if(expire != 0){
		var exdate = new Date();
		exdate.setDate(exdate.getDate() + expire);
		expireStr = ";expires=" + exdate;
	}
	document.cookie = name + "=" + escape(value) + expireStr + ";path=/;domain=.mstaml.com";
}

function GetCookie(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 unescape(c.substring(nameEQ.length, c.length)); }
	}
	return null;
}

function SavedSearch(save){
	if(save){
		if(!GetCookie('savedSearch') || confirm('يوجد لديك بحث محفوظ حالياً، هل تريد حفظ هذا البحث بدلاً من البحث القديم؟')){
			SetCookie('savedSearch', window.location, 365);
			alert("لقد تم حفظ هذا البحث في جهازك هذا بنجاح. ويمكنك الرجوع لهذا البحث عن طريق الضغط على \"البحث المحفوظ\" في قائمة الصفحات في أعلى الموقع");
		}
	}else{
		if(GetCookie('savedSearch')){ window.location = GetCookie('savedSearch'); }
		else{ window.location = 'http://www.mstaml.com/section/index.php?nss=1'; }
	}
}

function Most(show){
	var H1 = "fS1 w50p"; H1Click = "fS1 w50p fB"; H2 = "f12 w30p"; H2Click = "f12 w30p fB";
	if(show < 4){
		document.getElementById("mostViews").className = H1Click;
		document.getElementById("mostThreads").className = H1;
		document.getElementById("mostViewsMenu").className = "";
		document.getElementById("mostThreadsMenu").className = "none";
	}else{
		document.getElementById("mostViews").className = H1;
		document.getElementById("mostThreads").className = H1Click;
		document.getElementById("mostViewsMenu").className = "none";
		document.getElementById("mostThreadsMenu").className = "";
	}
	for(i = 1; i <= 6; i++){
		document.getElementById("mostLink" + i).className = H2;
		if(document.getElementById("most" + i) != null){ document.getElementById("most" + i).className = "none"; }
	}
	document.getElementById("mostLink" + show).className = H2Click;
	if(document.getElementById("most" + show) != null){ document.getElementById("most" + show).className = "fS1"; }
}



showItems = {'ads':[], 'frs':[]};

function TogglePM(action, id, name){
	if(!name){ name = 'item'; }
	if(document.getElementById(name + id)){
		if(action == 'show' || (action == 'toggle' && (document.getElementById(name + id).style.display == 'none' || document.getElementById(name + id).style.display == ''))){
			document.getElementById(name + id).style.display = 'block';
			$('#' + 'plusminus' + id).removeClass('iconPlus').addClass('iconMinus');
			return 1;
		}else{
			document.getElementById(name + id).style.display = 'none';
			$('#' + 'plusminus' + id).removeClass('iconMinus').addClass('iconPlus');
			return 2;
		}
	}
	return 0;
}

function Toggle(action, id){ 
	if(document.getElementById(id)){
		if(action == 'show' || (action == 'toggle' && (document.getElementById(id).style.display == 'none' || document.getElementById(id).style.display == ''))){
			document.getElementById(id).style.display = 'block';
		}else{
			document.getElementById(id).style.display = 'none';
		}
	}
}

function ItemsToggle(action, name, ids, meta){
	for(var i in ids){
		switch(TogglePM(action, ids[i] + '', name)){
			case 1: 
				if(action == 'show' || meta){
					$('#box' + name + ids[i]).css({"border-radius": "5px 5px 0 0", "margin-bottom": "0"});
					Toggle('hide', 'meta' + name + ids[i]);
					Images.SwitchItemImages(name == 'item' ? 'ads' : 'frs', ids[i]);
				}
				break;
			case 2: 
				if(action == 'hide' || meta){
					$('#box' + name + ids[i]).css({"border-radius": "5px"});
					Toggle('show', 'meta' + name + ids[i]); 
				} 
				break;
		}
	}
}

function ItemToggle(i, meta){ ItemsToggle('toggle', 'item', [i], meta); }
function FrToggle(i, meta){ ItemsToggle('toggle', 'fr', [i], meta); }
function TPM(id){ TogglePM('toggle', id); }

function RowShowHide(value, field){
	if(value < 0){ document.getElementById(field).style.display = ""; }
	else{ document.getElementById(field).style.display = "none"; }
}

function EnableDisableDateControlles(value){
	var disable = value < 0 ? false : true ;
	document.form.sd.disabled = disable; 
	document.form.sm.disabled = disable; 
	document.form.sy.disabled = disable; 
	document.form.ed.disabled = disable; 
	document.form.em.disabled = disable; 
	document.form.ey.disabled = disable; 
}

function CountryShowHide(){
	if(document.form.country[22].selected){ document.getElementById("countryOtherID").style.display = "block"; }
	else{ document.getElementById("countryOtherID").style.display = "none"; }
	if(document.form.country[7].selected){ document.form.city.disabled = false; }
	else{ document.form.city.disabled = true; }
}

function Hint(field, focus){
	if(field.name){ fieldName = field.name + 'Hint'; }else{ fieldName = field + 'Hint'; }
	if(focus){
		document.getElementById(fieldName).className = "gO1";
	}else{
		document.getElementById(fieldName).className = "";
	}
}



var messages = new Object();
messages.agreement = 'عفواً.. يجب الموافقة على اتفاقية استخدام الموقع';
messages.username = 'عفواً.. يجب إضافة اسم المستخدم، وبشكل صحيح، وأن لا يقل طوله عن ثلاثة خانات';
messages.usernameCorrect = 'عفواً.. يجب أن لا يحتوي اسم المستخدم على مسافات، ويجب اتباع الشرح الظاهر';
messages.password = 'عفواً.. يجب إضافة كلمة السر، وأن لا يقل طولها عن أربعة خانات';
messages.passwordIdentical = '"عفواً.. يجب أن تتطابق خانة "كلمة السر" مع خانة "تأكيد كلمة السر';
messages.passwordNumbers = 'عفواً.. يجب إضافة الرقم السري، وأن يتكون من أربعة أرقام';
messages.passwordGeneral = 'عفواً.. يجب إضافة الرقم السري';
messages.emailIdentical = '"عفواً.. يجب أن تتطابق خانة "البريد الإلكتروني" مع خانة "تأكيد البريد الإلكتروني';
messages.url = 'عفواً.. يجب إضافة رابط متجرك الإلكتروني، وأن يتكون من حروف إنجليزية و/أو أرقام فقط، وأن يبدأ بحرف، وأن لا يقل طوله عن 3 خانات';
messages.shop = 'عفواً.. يجب إضافة اسم متجرك الإلكتروني';
messages.email = 'عفواً.. يجب إضافة البريد الإلكتروني، وبشكل صحيح';
messages.mobile = 'عفواً.. يجب إضافة رقم الجوال، وأن يبدأ بالخط الدولي، وبدون أصفار أو أي علامات أخرى';
messages.phone = 'عفواً.. خانة الهاتف اختيارية، يمكنك تركها فارغة، أو كتابة أرقام صحيحة فيها، ويمكنك فصل الأرقام بالعلامة "-" فقط';
messages.other = 'عفواً.. خانة طريقة اتصال أخرى اختيارية، يمكنك تركها فارغة، أو كتابة أرقام صحيحة فيها، ويمكنك فصل الأرقام بالعلامة "-" فقط';
messages.country = 'عفواً.. يجب إضافة الدولة وباللغة العربية';
messages.city = 'عفواً.. يجب اختيار المدينة';
messages.fullname = 'عفواً.. يجب إضافة الاسم الكامل، وباللغة العربية، وبشكل صحيح';
messages.name = 'عفواً.. يجب إضافة الاسم، وبشكل صحيح';
messages.birthdate = 'عفواً.. يجب التأكد من صحة تاريخ الميلاد';
messages.date = 'عفواً.. يجب اختيار التاريخ الصحيح';
messages.bid = 'عفواً.. يجب إضافة المزايدة، وبشكل صحيح، وأن لا تقل عن ما هو مذكور';
messages.thread = 'عفواً.. يجب إضافة الرد';
messages.message = 'عفواً.. يجب أن تضيف رسالتك';
messages.maximum = 'عفواً.. يجب أن لا يزيد عدد حروف هذه الخانة عن ';
messages.quickly = 'عفواً.. يجب ملء الخانة';
messages.captcha = 'عفواً.. يجب كتابة الرقم الظاهر في الصورة، وبشكل صحيح';
messages.correct = 'عفواً.. يجب التأكد من صحة ودقة المعلومات، والموافقة على النقطتين الأخيرتين في قسم إرسال الطلب';
messages.adID = 'عفواً.. يجب إضافة رقم الإعلان، وبشكل صحيح';
messages.period = 'عفواً.. يجب اختيار الفترة المطلوبة';
messages.bank = 'عفواً.. يجب اختيار البنك الذي تم فيه الإيداع';
messages.tad = 'عفواً.. يجب اختيار نوع الإعلان المطلوب';
messages.accountName = 'عفواً.. يجب إضافة اسم المودع أو صاحب الحساب البنكي';
messages.accountNumber = 'عفواً.. يجب إضافة رقم الحساب الذي تم التحويل منه، أو صفر في حال الإيداع';
messages.money = 'عفواً.. يجب إضافة المبلغ بالريال السعودي، وبشكل صحيح';
messages.type = 'عفواً.. يجب أن تختار القسم المناسب لإعلانك';
messages.brand = 'عفواً.. يجب أن تختار الشركة';
messages.model = 'عفواً.. يجب أن تحدد السنة';
messages.division = 'عفواً.. يجب أن تختار المنتدى المناسب لموضوعك';
messages.location = 'عفواً.. يجب أن تختار المكان الذي توجد به البضاعة أو الخدمة';
messages.subjectItem = 'عفواً.. يجب أن تضيف عنوان الإعلان';
messages.subjectFr = 'عفواً.. يجب أن تضيف عنوان الموضوع';
messages.bodyItem = 'عفواً.. يجب أن تضيف مواصفات الإعلان';
messages.bodyFr = 'عفواً.. يجب أن تضيف الموضوع';
messages.bidStart = 'عفواً.. يجب أن تضيف قيمة لبداية المزاد وأن تكون عدد صحيح بدون كسور';
messages.commission = 'عفواً.. يجب الموافقة على عمولة موقع مستعمل';
messages.kashida = 'عفواً.. يجب أن لا تحتوي هذه الخانة على علامة "_" لتمديد الحروف العربية، وذلك لضمان ظهور هذه الخانة عند البحث';
messages.contactsUser = 'تنبيه: لا ننصح بإضافة أرقام اتصالك في خانة المواصفات، لأنها قد تبقى في محركات البحث حتى بعد حذف الإعلان، وقد تقوم مواقع أخرى بنسخها آلياً وإعادة نشرها، مما يسبب لك اتصالات مزعجة. الأفضل وضعها في بطاقتك أدناه، حيث يصعب نسخها آلياً من هناك';
messages.contactsVisitor = 'تنبيه: لا ننصح بإضافة أرقام اتصالك في خانة المواصفات، لأنها قد تبقى في محركات البحث حتى بعد حذف الإعلان، وقد تقوم مواقع أخرى بنسخها آلياً وإعادة نشرها، مما يسبب لك اتصالات مزعجة. الأفضل الاكتفاء برقم جوالك المذكور أعلاه، حيث يصعب نسخه آلياً';
messages.numbers = 'عفواً.. يجب إضافة أرقام فقط';
messages.sure1 = 'هل أنت متأكد؟';

var integerPattern = /^[0-9\u0660-\u0669]+$/;
var floatPattern = /^[0-9\u0660-\u0669]+(?:[\.\u066b][0-9\u0660-\u0669]+)?$/;
var phonePattern = /^[0-9\u0660-\u0669\- ]+$/;
var mobilePattern = /^[1-9\u0661-\u0669][0-9\u0660-\u0669]+$/;
var arabicPattern = /^[ابتثجحخدذرزسشصضطظعغفقكلمنهويأإآىئؤءة ]+$/;
var urlPattern = /^[a-zA-Z]([0-9a-zA-Z]){2,29}$/;
var emailPattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+[a-zA-Z0-9]{2,4}$/;

function CorrectUsername(field){
	var orig = field.value;
	while(field.value.indexOf(" ") != -1){ field.value = field.value.replace(" ", ""); }
	while(field.value.indexOf("ـ") != -1){ field.value = field.value.replace("ـ", ""); }
	while(field.value.indexOf(".") != -1){ field.value = field.value.replace(".", ""); }
	while(field.value.indexOf("--") != -1){ field.value = field.value.replace("--", "-"); }
	while(field.value.indexOf("__") != -1){ field.value = field.value.replace("__", "_"); }
	field.value = field.value.replace(/(\S)\1{2,}/g, "$1$1");
	if(field.value != orig){ alert(messages['usernameCorrect']); }
}

function RemoveKashida(field, msg){
	if(field.value.indexOf("ـ") != -1){
		if(msg){ alert(messages.kashida); }
		field.value = field.value.replace(/ـ/g, "");
	}
}

function RemoveSpaces(field){
 var tmp = field.value.replace(/  +/g, " ");
 if(tmp != field.value){
  field.value = tmp;
 } 
}

function RemoveDuplicate(field){
 var tmp = field.value.replace(/(.)\1{3,}/g, "$1$1$1");
 if(tmp != field.value){
  field.value = tmp;
 } 
}

var alertDone = 0;
function RemoveContacts(field, visitor){
	if(visitor){ msg = messages.contactsVisitor; }else{ msg = messages.contactsUser; }
	var contactsPattern = /(?:0|966)5[0-9]{8}/;
	if(!alertDone && contactsPattern.test(field.value)){ alertDone = 1; alert(msg); }
}

function CheckTextArea(field, max){
	if(field.value.length > max){ 
		alert(messages.maximum + max);
		field.value = field.value.substring(0, max); 
		field.focus();
	}
}

function CheckQuick(x){
	Q = document.frmQuick;
	Q.x.value = Utils.Trim(Q.x.value);
	if(Q.x.value.length < 1){ alert(messages.quickly); Q.x.focus(); return false; }
	data = Q.x.value;
	Q.action = "http://www.mstaml.com/";
	Q.fi.disabled = true; Q.i.disabled = true; Q.u.disabled = true; Q.m.disabled = true; Q.un.disabled = true; Q.table.disabled = true; Q.x.disabled = true; // no need to send these in url
	if(x == 'ad'){ Q.i.disabled = false; Q.i.value = data; Q.action += "section/item.php"; }else
	if(x == 'fr'){ Q.i.disabled = false; Q.i.value = data; Q.action += "forum/fr.php"; }else
	if(x == 'fi'){ Q.fi.disabled = false; Q.fi.value = data; Q.action += "section/index.php"; }else
	if(x == 'm'){  Q.m.disabled = false; Q.m.value = data; Q.action += "section/item.php"; }else
	if(x == 'u'){  Q.u.disabled = false; Q.u.value = data; Q.action += "manage/user.php"; }else
	if(x == 'iAd'){ Q.target = "_blank"; Q.i.disabled = false; Q.table.disabled = false; Q.i.value = data; Q.table.value = "ad"; Q.action += "adm/item.php"; }else
	if(x == 'iFr'){ Q.target = "_blank"; Q.i.disabled = false; Q.table.disabled = false; Q.i.value = data; Q.table.value = "forum"; Q.action += "adm/item.php"; }else
	if(x == 'un'){ Q.target = "_blank"; Q.un.disabled = false; Q.un.value = data; Q.action += "adm/user.php"; }	
	Q.submit();
	Q.target = ""; 	Q.x.disabled = false; 	return true;
}

function FormVerify(settings, disableSubmit, form){
	if(!form){ form = document.form; }
	var fields = settings.split(","); // settings: fild|condition|message, sample: city|minimum:2|city, name|minimum:8|name, ...
	var i, field, type, fail;
	for(i = 0; i < fields.length; i++){
		field = fields[i].split("|");
		type = field[1].split(":");
		switch(type[0]){
			case "minimum":			if(form[field[0]].value.length < type[1]){ fail = 1; } break;
			case "minimumArabic":	if(!(arabicPattern.test(form[field[0]].value)) || (form[field[0]].value.length < type[1])){ fail = 1; } break;
			case "minimumSelect":	if(!form[field[0]].disabled && form[field[0]].options[form[field[0]].selectedIndex].value.length < type[1]){ fail = 1; } break;
			case "select":			if(!form[field[0]].disabled && form[field[0]].options[0].selected){ fail = 1; } break;
			case "check":			if(!form[field[0]].checked){ fail = 1; } break;
			case "url":				if(!(urlPattern.test(form[field[0]].value))){ fail = 1; } break;
			case "identical":		if(form[field[0]].value != form[type[1]].value){ fail = 1; } break;
			case "email":			if(!(emailPattern.test(form[field[0]].value))){ fail = 1; } break;
			case "phone":			if(!(phonePattern.test(form[field[0]].value)) || (form[field[0]].value.length < type[1])){ fail = 1; } break;
			case "mobile":			if(!(mobilePattern.test(form[field[0]].value)) || (form[field[0]].value.length < type[1])){ fail = 1; } break;
			case "integer":			if(!(integerPattern.test(form[field[0]].value)) || form[field[0]].value < 1){ fail = 1; } break;
			case "integerMinimum":	if(!(integerPattern.test(form[field[0]].value)) || form[field[0]].value < parseInt(type[1])){ fail = 1; } break;
			case "float":			if(!(floatPattern.test(form[field[0]].value)) || form[field[0]].value < 1){ fail = 1; } break;
			default:				if(form[field[0]].value.length < 1){ fail = 1; }
		}
		if(fail == 1){
			alert(messages[field[2]]);
			form[field[0]].focus();
			return false;
		}
	}
	// to know when user click back history
	if(
		typeof(form.back) == "object" && 
		typeof(form.formID) == "object"
	){
		var submittedFormIDs = GetCookie('submittedFormIDs') ? GetCookie('submittedFormIDs') : '';
		submittedFormIDs = submittedFormIDs.length ? submittedFormIDs.split(',') : [];
		submittedFormIDs[submittedFormIDs.length] = form.formID.value;
		SetCookie('submittedFormIDs', submittedFormIDs.toString(), 0); 
	}
	if(disableSubmit){
		var inputs = form.getElementsByTagName('input');
		for(i = 0; i < inputs.length; ++i){ if(inputs[i].type == 'submit'){ inputs[i].disabled = true; }}
	}
	return true;
}



function CheckRegister(isRegister){
	var toVerify = "agreed|check|agreement,";
	if(isRegister){ toVerify += "username|minimum:3|username,"; }
	toVerify += "password|minimum:4|password,";
	toVerify += "password2|identical:password|passwordIdentical,";
	if(document.form.country[22].selected){ toVerify += "countryOther|minimumArabic:3|country,"; }
	if(document.form.country[7].selected){ toVerify += "city|minimumSelect:2|city,"; }
	if(document.form.phone.value){ toVerify += "phone|phone:5|phone,"; }
	toVerify += "name|minimumArabic:10|fullname,";
	toVerify += "checkInfo1|check|correct,";
	toVerify += "checkInfo2|check|correct";
	return FormVerify(toVerify, 1);
}

function CheckItem(i, visitor){
	var toVerify = "";
	if(!i){
		if(visitor){ toVerify += "mobile|mobile:8|mobile,password|integer|passwordNumbers,password|minimum:4|passwordNumbers,"; }
		toVerify += "t|select|type,";
		toVerify += "b|select|brand,";
		toVerify += "m|select|model,";
		toVerify += "l|select|location,";
	}
	toVerify += "subject|minimum:3|subjectItem,";
	toVerify += "body|minimum:3|bodyItem,";
	if(!document.form.bidStart.disabled){ toVerify += "bidStart|integer|bidStart,"; }
	toVerify += "commission|check|commission";
	if(!i && visitor){ toVerify += ",captcha|minimum:4|captcha"; }
	return Images.CheckImages() && FormVerify(toVerify, 1);}

function CheckFr(i){
	var toVerify = "";
	if(!i){ toVerify += "f|select|division,"; }
	toVerify += "subject|minimum:3|subjectFr,";
	toVerify += "body|minimum:3|bodyFr";
	return Images.CheckImages() && FormVerify(toVerify, 1);}

function CheckShop(){
	return FormVerify("url|url:3|url,name|minimum:3|shop", 1);
}

function CheckVerify(){
	return FormVerify("password|minimum:4|password", 1);
}

function CheckLogin(){
	return FormVerify(
		"username|minimum:3|username," +
		"password|minimum:4|password"
		,1
	);
}

function CheckForget(){
	return FormVerify("email|email|email,captcha|minimum:4|captcha", 1);
}

function CheckPassword(){
	return FormVerify("password|minimum:4|password,password2|identical:password|passwordIdentical" ,1);
}

function CheckEmailNew(){
	return FormVerify("email|email|email,email2|identical:email|emailIdentical" ,1);
}

function CheckContact(user){
	if(user){ return FormVerify("body||message", 1); }
	else{ return FormVerify("body||message,email|email|email,captcha|minimum:4|captcha", 1); }
}

function CheckInternalSend(){
	return FormVerify("username|minimum:3|username,body||message" ,1);
}

function CheckInternalVisitor(){
	return FormVerify("body||message,name||name,email|email|email,captcha|minimum:4|captcha" ,1);
}

function CheckVisitorAd(){
	var toVerify = "";
	if(document.form.action[0].checked){ toVerify += "body||thread,"; }
	toVerify += "password||passwordGeneral,captcha|minimum:4|captcha";
	return (document.form.action[1].checked || confirm(messages.sure1)) && FormVerify(toVerify, 1);}

function CheckPayableServices(uid, special, fixed, tads, broker){
	var toVerify = "";
	if(!uid && (special || broker)){ toVerify += "username|minimum:3|username,"; }
	toVerify += "name|minimum:3|name,";
	toVerify += "mobile|phone:5|mobile,";
	toVerify += "email|email|email,";
	if(fixed || tads) toVerify += "type|select|tad,";
	if(special || fixed || tads) toVerify += "period|select|period,";
	if(fixed || broker) toVerify += "adID|integer|adID,";
	toVerify += "bank|select|bank,";
	toVerify += "day|select|date,";
	toVerify += "month|select|date,";
	toVerify += "accountName|minimum:3|accountName,";
	toVerify += "accountNumber||accountNumber,";
	toVerify += "amount|float|money";
	if(!uid) toVerify += ",captcha|minimum:4|captcha";
	return FormVerify(toVerify, 1);
}

function CheckBid(bidMinAllowed){
	return FormVerify("body|integerMinimum:" + bidMinAllowed + "|bid", 1);
}

function CheckThread(){
	return FormVerify("body||thread", 1);
}

function CheckEmail(){
	return FormVerify("name|minimum:3|name,email|email|email" ,1);
}

function CheckMobile(){
	document.form.mobile = document.form.mobile.split(' ').join(''); // remove any spaces
	return FormVerify("mobile|mobile:8|mobile" ,0);
}



var Fixed = {
	defaults : {
		forum: 0,
		order : 0,
		seed : 1,
		pages : [],
		itemsInRow : 0,
		start : true,
		switchOneThumbCounters : {},
		switchThumbId : null,
		switchOneThumbInterval: null,
		anims: {},
		thumbPrefix : 'Image',
		animInterval: 40, // 40 will give us 25 frames/second animation if cpu is not busy.
		animDuration: 1000
	},
	
	Write : function(divID){
		if(Fixed[divID].pages.length){
			if(typeof(Fixed[divID].start) == 'undefined'){
				Fixed[divID].start = false;
				// copy default values
				for(var index in Fixed.defaults){
					if(typeof(Fixed[divID][index]) == 'undefined'){
						if(Fixed.defaults[index] instanceof Array){
							Fixed[divID][index] = [];
						}else if(typeof(Fixed.defaults[index]) == 'object'){
							Fixed[divID][index] = {};
						}else{
							Fixed[divID][index] = Fixed.defaults[index];
						}
					}
			}
				Fixed.SetupPages(divID); 
			}
			for(var i = 0; i < Fixed[divID].pages.length; ++i){
				$('#fixedPageButton' + i).css('color', Fixed[divID].order == i ? 'red' : '');
			}
			var output = '<table><tr>';
			for(var i = 0; i < Fixed[divID].pages[Fixed[divID].order].length; i++){
				output += '<td class="xCenter xTop"><div class="center w93"><a href="' + (Fixed[divID].forum ? ' /forum/fr.php?i=' : '/section/item.php?i=') + Fixed[divID].pages[Fixed[divID].order][i].id + '" class="boxFixed">';
				if(Fixed[divID].pages[Fixed[divID].order][i].bundle){
					var id = '';
					if(Fixed[divID].pages[Fixed[divID].order][i].images > 1){
						id = 'id="' + divID + Fixed[divID].thumbPrefix + Fixed[divID].pages[Fixed[divID].order][i].id + '" ';
					}
					output += '<span ' + id + 'class="imgThumb" style="background-image: url(\'/imagesData/' + Fixed[divID].pages[Fixed[divID].order][i].bundle + '\'); background-position: 0px 0px;"></span>';
				}else{
					output += '<span class="imgThumb icon' + (Fixed[divID].forum ? 'F' + Fixed[divID].pages[Fixed[divID].order][i].division : 'S' + Fixed[divID].pages[Fixed[divID].order][i].section) + 'B"></span>';
				}
				output += '<br>' + Utils.EscapeHTML(Fixed[divID].pages[Fixed[divID].order][i].title);
				output += '</a></div></td>';
				if(!((i + 1) % Fixed[divID].itemsInRow)){ output += '</tr><tr>'; }
			}
			output += '</tr></table>';
			$('#' + divID).html(output);
			for(var i = 0; i < Fixed[divID].pages[Fixed[divID].order].length; i++){
				$('#' + divID + Fixed[divID].thumbPrefix + Fixed[divID].pages[Fixed[divID].order][i].id).mouseover(function(){
					Fixed[divID].switchThumbId = ($(this).attr('id')).substr((divID + Fixed[divID].thumbPrefix).length);
					Fixed.SwitchOneThumb(divID);
					if(Fixed[divID].switchOneThumbInterval){ clearInterval(Fixed[divID].switchOneThumbInterval); }
					Fixed[divID].switchOneThumbInterval = window.setInterval('Fixed.SwitchOneThumb(\'' + divID + '\')', 2000);
			});
				$('#' + divID + Fixed[divID].thumbPrefix + Fixed[divID].pages[Fixed[divID].order][i].id).mouseout(function(){
					clearInterval(Fixed[divID].switchOneThumbInterval);
			});
		}
		}
	},
	
	SwitchPage : function(divID, i){
		clearInterval(Fixed[divID].switchOneThumbInterval);
		for(var index in Fixed[divID].switchOneThumbCounters){
			Fixed[divID].switchOneThumbCounters[index] = 0;
		}
		Fixed[divID].order = i;
		Fixed.Write(divID);
	},
	
	SetupPages : function(divID){
		var output = '';
		for(var i = 0; i < Fixed[divID].pages.length; i++){
			output += '<a id="fixedPageButton' + i + '" href="javascript: void(0)" onclick="Fixed.SwitchPage(\'' + divID + '\', ' + i + ');" class="f20 fB p5">&bull;</a>';
		}
		$('#fixedButtons').html(output);
		var sortBy = function(a,b){ return ((parseInt(a.id) % Fixed[divID].seed) > (parseInt(b.id) % Fixed[divID].seed)) ? 1 : -1; };
		for(var i = 0; i < Fixed[divID].pages.length; ++i){
			var fixed = [];
			var free = [];
			for(var j = 0; j < Fixed[divID].pages[i].length; ++j){
				if(Fixed[divID].pages[i][j].fixed == "1"){
					fixed[fixed.length] = Fixed[divID].pages[i][j];
				}else{
					free[free.length] = Fixed[divID].pages[i][j];
				}
			}
			fixed.sort(sortBy);
			free.sort(sortBy);
			Fixed[divID].pages[i] = [].concat(fixed, free);
		}
	},	
	
	SwitchOneThumb : function(divID){
		Fixed[divID].switchOneThumbCounters[Fixed[divID].thumbPrefix + Fixed[divID].switchThumbId] = 
			typeof(Fixed[divID].switchOneThumbCounters[Fixed[divID].thumbPrefix + Fixed[divID].switchThumbId]) == 'undefined' ?
			1 :
			Fixed[divID].switchOneThumbCounters[Fixed[divID].thumbPrefix + Fixed[divID].switchThumbId] + 1;  
		var itemIndex = Utils.FindObjectInArray(Fixed[divID].pages[Fixed[divID].order], {"id": Fixed[divID].switchThumbId});
		Utils.Log('itemIndex' + itemIndex);
		if(Fixed[divID].pages[Fixed[divID].order][itemIndex].images > 1){
			if((Fixed[divID].switchOneThumbCounters[Fixed[divID].thumbPrefix + Fixed[divID].switchThumbId] % Fixed[divID].pages[Fixed[divID].order][itemIndex].images) == 0){
				$('#' + divID + Fixed[divID].thumbPrefix + Fixed[divID].pages[Fixed[divID].order][itemIndex].id).css({"background-position": "0px 64px"});
			}
			Fixed.Animate(
				divID,
				Fixed[divID].pages[Fixed[divID].order][itemIndex].id,
				-1 * 64 * (Fixed[divID].switchOneThumbCounters[Fixed[divID].thumbPrefix + Fixed[divID].switchThumbId] % Fixed[divID].pages[Fixed[divID].order][itemIndex].images),
				1);
		}
	},
	
	Animate: function(divID, id, to, start){ // not used right now
		if(!start && Fixed[divID].anims[id].elem){
			var now = (new Date()).getTime();
			var timediff = now - Fixed[divID].anims[id].start;
			if(timediff < Fixed[divID].animDuration){
				Fixed[divID].anims[id].elem.style.backgroundPosition = '0px ' + (Fixed[divID].anims[id].from + (timediff / Fixed[divID].animDuration) * Fixed[divID].anims[id].diff) + 'px';
				window.setTimeout('Fixed.Animate(\'' + divID + '\', ' + id + ')', Fixed[divID].animInterval);
			}else{
				Fixed[divID].anims[id].elem.style.backgroundPosition = '0px ' + Fixed[divID].anims[id].to + 'px';
			}
			return;
		}
		if(!Fixed[divID].anims[id]){
			Fixed[divID].anims[id] = {};
		}
		if(start){
			Fixed[divID].anims[id].elem = document.getElementById(divID + Fixed[divID].thumbPrefix + id);
			Fixed[divID].anims[id].start = (new Date()).getTime();
			Fixed[divID].anims[id].from = parseFloat(Fixed[divID].anims[id].elem.style.backgroundPosition.split(' ')[1].replace(/[^\-0-9.]/gi, ''));
			Fixed[divID].anims[id].to = to;
			Fixed[divID].anims[id].diff = Fixed[divID].anims[id].to - Fixed[divID].anims[id].from;
			window.setTimeout('Fixed.Animate(\'' + divID + '\', ' + id + ')', Fixed[divID].animInterval);
		}
	}
}



var Popup = {
	"content" : null,
	
	"Init" : function(){
		Popup.content = $('<div></div>').dialog({
			autoOpen: false,
			modal: true,
			beforeClose: function(event, ui) { Popup.content.html(''); },
			dialogClass: "flora"
		});
		$('.flora.ui-dialog').css({position:"fixed"});
	},

	"Open" : function(kind, value, external){
		if(kind == 'website'){
			Popup.content.dialog("option", {title: "<a onclick=\"Popup.content.dialog('close'); return true\" target=\"_blank\" class=\"pl30\" href=\"" + Utils.EscapeHTML(value) + "\">[فتح في صفحة مستقلة]</a> <img id=\"popupLoading\" width=\"128\" height=\"15\" class=\"xBottom\" src=\"/images/uploading.gif\">", width: $(window).width() * 0.75, height: $(window).height() * 0.75, position: "center"});
			Popup.content.html('<iframe id="popupBody" class="block center xCenter w100p h100p" type="text/html" frameborder="0" src="' + Utils.EscapeHTML(external ? 'http://www.mstaml.com/out.php?l=' + escape(value) : value) + '"></iframe>')
			$("#popupBody").bind("load", function () { $("#popupLoading").remove(); });
		}else if(kind == 'image'){
			Popup.content.dialog("option", {title: "<a onclick=\"Popup.content.dialog('close'); return true\" target=\"_blank\" class=\"pl30\" href=\"" + Utils.EscapeHTML(value) + "\">[فتح في صفحة مستقلة]</a> <img id=\"popupLoading\" width=\"128\" height=\"15\" class=\"xBottom\" src=\"/images/uploading.gif\">", width: 720, height: 450, position: "center"});
			Popup.content.html('<div class="block center xCenter w100p h100p"><img id="popupBody" src="' + Utils.EscapeHTML(external ? 'http://www.mstaml.com/out.php?l=' + escape(value) : value) + '"></div>')
			var img = $("#popupBody");
			img.bind("load", function (){
				$("#popupLoading").remove();
				var widthOrg = img.width();
				if(img.width() > 680){
					img.css("width", "680px");
					img.click(function(){
						if(img.width() != widthOrg){
							img.css("width", widthOrg + "px");
						}else{
							img.css("width", "680px");
						}
					});
				}
			});
			img.error(function () { Popup.content.html('<p class="wng mt20">عفواً.. الصورة لم تعد موجودة، أو أن الرابط غير صحيح.</p>'); $("#popupLoading").remove(); });
		}else if(kind == 'youtube'){
			Popup.content.dialog("option", {title: "<a onclick=\"Popup.content.dialog('close'); return true\" target=\"_blank\" class=\"pl30\" href=\"" + Utils.EscapeHTML(value) + "\">[فتح في صفحة مستقلة]</a> <img id=\"popupLoading\" width=\"128\" height=\"15\" class=\"xBottom\" src=\"/images/uploading.gif\">", width: 720, height: 450, position: "center"});
			Popup.content.html('<iframe id="popupBody" class="block center xCenter w100p h100p" type="text/html" frameborder="0" src="' + Utils.EscapeHTML('http://www.mstaml.com/out.php?l=' + escape('http://www.youtube.com/embed/' + Utils.ParseQuery(value).v + '?rel=0')) + '"></iframe>')
			$("#popupBody").bind("load", function () { $("#popupLoading").remove(); });
		}
		Popup.content.dialog("open");
		$(".ui-widget-overlay").click(function(){ Popup.content.dialog("close"); });
		return false; // prevent the default action, e.g., following a link
	}
}



var Forms = {
	"modalDialog" : null,
	
	"Init" : function(){
		Forms.modalDialog = $('<div></div>').dialog({
			autoOpen: false,
			modal: true,
			beforeClose: function(event, ui) { Forms.modalDialog.html(''); },
			dialogClass: "flora"
		});
		$('.flora.ui-dialog').css({position:"fixed"});
	},
	
	"inviteFriend" : {
		enableSubmit : function(form){
			var inputs = form.getElementsByTagName('input');
			for(i = 0; i < inputs.length; ++i){ if(inputs[i].type == 'submit'){ inputs[i].disabled = (formIDStatus == 1 ? false : true); }}
		},
		"open" : function(id, title, formID){
			Forms.modalDialog.dialog("option", {title: "دعوة صديق", width: 600, height: 400, position: "center"});
			Forms.modalDialog.html('\
				<form name="formInviteFriend" method="post" action="" onsubmit="Forms.inviteFriend.post(' + id + ',\'' + formID + '\'); return false">\
				<p id="formInviteFriendErrorMsg" class="wng"></p>\
				<div class="boxDarkHead w500">دعوة صديق لقراءة:<br>' + title + '</div>\
				<div class="boxDarkBody w500"><table>\
					<tr>\
						<td class="label pt10">اسمك<span class="wng">*</span></td>\
						<td class="field pt10"><input type="text" name="name" value="" maxlength="100" class="w180"></td>\
					</tr><tr>\
						<td class="label">بريد صديقك الإلكتروني<span class="wng">*</span></td>\
						<td class="field"><input type="text" name="email" value="" maxlength="100" class="w180 ltr xLeft"></td>\
					</tr><tr>\
						<td class="label">تعليقك</td>\
						<td class="field"><textarea name="note" rows="3" cols="35" onkeyup="CheckTextArea(this, window.threadMaxSize);"></textarea></td>\
					</tr><tr>\
						<td class="xCenter pt10" colspan="2">\
							<input type="submit" name="submit" value="   إرسال   ">\
							<span id="formInviteFriendBusy" style="display: none;"><img src="/images/loading.gif" style="width: 20px; height: 20px"></span>\
							<p class="hintSmall"><span class="wng">*</span> تعني: يجب ملء الخانة</p>\
						</td>\
					</tr>\
				</table></div>\
				</form>')
			Forms.modalDialog.bind("dialogclose", function(event, ui){
				if(Forms.modalDialogAjax){
					Forms.modalDialogAjax.abort();
					Forms.modalDialogAjax = null;
				}
				Forms.modalDialog.html('');
			});
			Forms.modalDialog.dialog("open");
			// prevent the default action, e.g., following a link
			return false;
		},
		"post" : function(id, formID){
			if(FormVerify("name|minimum:3|name,email|email|email" , 1, document.formInviteFriend)){
				$('#formInviteFriendBusy').show();
				Forms.modalDialogAjax = $.ajax({
					type: "POST",
					url: 'http://www.mstaml.com/manage/email.php?ia=' + id + '&ajax=1',
					dataType: "text",
					data: {
						"name": document.formInviteFriend.name.value,
						"email": document.formInviteFriend.email.value,
						"note": document.formInviteFriend.note.value,
						"formID" : formID
					},
					success: function(response){
						Utils.Log(response);
						try {
							response = $.parseJSON(response);
							if(response.formStatus > 0){
								Forms.modalDialog.html('<p class="don">لقد تم إرسال دعوتك بنجاح. <a href="javascript: Forms.modalDialog.dialog(\'close\'); void(0)">إغلاق</a></p>');
							}else{
								switch(response.formStatus){
									case -1: document.getElementById('formInviteFriendErrorMsg').innerHTML = 'عفواً.. يجب أن تضيف إسمك وبشكل صحيح.'; break;
									case -2: document.getElementById('formInviteFriendErrorMsg').innerHTML = 'عفواً.. يجب أن تضيف بريد صديقك وبشكل صحيح.'; break;
									case -3: document.getElementById('formInviteFriendErrorMsg').innerHTML = 'عفواً.. لم يتم الإرسال، نرجو التأكد من صحة البريد الإلكتروني والمحاولة مرة أخرى.'; break;
								}
								Forms.enableSubmit(document.formInviteFriend);
							}
						} 
						catch(e){
							alert(Images.msgErrorInternet + "\n(21)");
						}
						Forms.modalDialogAjax = null;
					},
					error: function (XMLHttpRequest, textStatus, errorThrown){
						Utils.Dir(XMLHttpRequest);
						Utils.Dir(textStatus);
						Utils.Dir(errorThrown);
						Forms.modalDialogAjax = null;
						if(!errorThrown.abort){
							alert(Images.msgErrorInternet + "\n(20)");
						}
					}
				});
			}
		}
	}
}



var Images = {
	"thumbWidth" : 64,
	"thumbHeight" : 64,
		"maxImageSize" : 4194304,
	"maxImageCount" : 30,
	"maxImageTotalSize" : 5242880,
	"progressInterval" : 5000,
	"fileNameMaxLength" : 30,
	"uploadedPath" : '/imagesData/',
	//"initialFormImages" : [], this will be set dynamically if we have form images
	"uploadedImages" : {},
	"uploadedImagesCount" : 0,
	"uploadedImagesTotalSize" : 0,
	"localFileNames" : {},
	"currentUploadIFrameDoc" : null,
		"items" : {"ads" : {}, "frs" : {}},
		"loading" : 1,
		"preloader" : new Array,
		"msgErrorInternet" : "عفواً.. حصل خطأ في الاتصال بالإنترنت، يرجى المحاولة مرة أخرى أو مراسلتنا",
	"msgErrorWrongImage" : "عفواً.. يجب أن تكون الصورة من الأنواع المذكورة، وأن لا يزيد حجمها عن أربعة ميقابايت",
	
		
	"SetImages" : function (kind, id, images){ // used to get images from html to javascript
		Images.items[kind][id] = images;
	},
	
	"WriteItemSlides" : function (list){ // loop over all items
		for(var kind in Images.items){
			for(var id in Images.items[kind]){
				Images.WriteSlide(kind, id, Images.loading, list);
			}
		}
	},
	
	"WriteSlide" : function (kind, id, loading, list){ // write the slide html for one item
		if(typeof(Images.items[kind][id]) == 'object' && Images.items[kind][id].bundle){
			var output = '';
			if(Images.items[kind][id].images.length > 1){
				output += 
					'<div class="mb10 fS1">' +
						'| <a href="javascript: Images.WriteSlide(\'' + kind + '\',' + id + ', 0, 1);">جميع الصور</a> ' +
						'| <a href="javascript: Images.WriteSlide(\'' + kind + '\',' + id + ', 0, 0);">معرض صور</a> |' + 
					'</div>';
			}
			for(var i = 0; i < Images.items[kind][id].images.length; ++i){
				if(list){
					output += '<div class="mt20">'
						+ '<img '
							+ 'width="' + Images.items[kind][id].images[i].width + '" '
							+ 'height="' + Images.items[kind][id].images[i].height + '" '
							+ 'src="/imagesData/' + Images.items[kind][id].images[i].name + '" '
							+ 'class="dAAA xBottom" '
							+ 'alt="' + Utils.EscapeHTML(Images.items[kind][id].images[i].description) + '" '
							+ 'title="' + Utils.EscapeHTML(Images.items[kind][id].images[i].description) + '" '
						+ '>'
						+ '<p class="fS1">'
							+ (i + 1)
							+ (Images.items[kind][id].images[i].description ? ('. ' + Utils.EscapeHTML(Images.items[kind][id].images[i].description)) : '')
						+ '</p></div>';
				}else if(Images.items[kind][id].images.length > 1){
					output += '<div class="inlineBlock mt2 fS1"><a href="javascript:void(0)" '
							+ 'onclick="Images.SwitchImage(\'' + kind + '\', ' + id + ', ' + i + ');" '
							+ 'alt="' + Utils.EscapeHTML(Images.items[kind][id].images[i].description) + '" '
							+ 'title="' + Utils.EscapeHTML(Images.items[kind][id].images[i].description) + '" '
							+ 'class="imgThumb"'
							+ 'style="background-image: url(\'/imagesData/' + Images.items[kind][id].bundle + '\'); background-position: 0px ' + (-1 * i * Images.thumbHeight) + 'px;">'
							+ '</a><br>' + (i + 1) + '</div>';
				}
				if(!loading && !list){ Images.Preload([Images.uploadedPath + Images.items[kind][id].images[i].name]); }
			}
			if(!list){
				output += (Images.items[kind][id].images.length > 1 ? '<br><br>' : '')
					+ '<img '
						+ 'id="image-' + kind + '-' + id + '" '
						+ 'width="' + Images.items[kind][id].images[0].width + '" '
						+ 'height="' + Images.items[kind][id].images[0].height + '" '
						+ 'src="' + (loading ? '/images/loading.gif' : '/imagesData/' + Images.items[kind][id].images[0].name) + '" '
						+ 'class="dAAA xBottom" '
						+ 'alt="' + Utils.EscapeHTML(Images.items[kind][id].images[0].description) + '" '
						+ 'title="' + Utils.EscapeHTML(Images.items[kind][id].images[0].description) + '">'
					+ '<p class="fS1" id="desc-' + kind + '-' + id + '">' + Utils.EscapeHTML(Images.items[kind][id].images[0].description) + '</p>';
			}
			document.getElementById('image-div-' + kind + '-' + id).innerHTML = output;
		}
	},
	
	"SwitchItemImages" : function (kind, id){ 		var i;
		if(Images.items[kind][id]){
			for(i in Images.items[kind][id].images){
				Images.Preload([Images.uploadedPath + Images.items[kind][id].images[i].name]);
			}
			Images.SwitchImage(kind, id, 0);
		}
	},
	
	"SwitchImage" : function (kind, id, i){ // switch loading image with actual image
		var imgID = 'image-' + kind + '-' + id;
		var img = document.getElementById(imgID);
		if(img){
			img.src = '/imagesData/' + Images.items[kind][id].images[i].name;
			img.width = Images.items[kind][id].images[i].width;
			img.height = Images.items[kind][id].images[i].height;
			img.alt = Images.items[kind][id].images[i].description;
			img.title = Images.items[kind][id].images[i].description;
			document.getElementById('desc-' + kind + '-' + id).innerHTML = Utils.EscapeHTML(Images.items[kind][id].images[i].description);
		}
	},
	
	"Preload" : function (imagePath){ // get image from server
		var image = new Image;
		image.src = imagePath;
		Images.preloader.push(image);
	},
	
		
	"ShowFormImages" : function (){ // show uploaded images from database for updating items. This is called by autorun
		Images.AddUploadIFrame();
		for(var index in Images.initialFormImages){
			if(Images.initialFormImages[index]){
				Images.AddImage(Images.initialFormImages[index]);
			}
		}
	},
	
	"SetNumbers" : function(){
		var i = 0;
		for(var index in Images.uploadedImages){
			$('#num-' + Images.uploadedImages[index].id).text(++i);
		}
	},
	
	"AddImage" : function (image){ // show one original/uploaded image in the form and update the vars
		Images.uploadedImagesCount += 1;
		Images.uploadedImagesTotalSize += parseInt(image.size);
		Images.uploadedImages[image.id] = image;
		$('#uploadedImageList').append(
			'<div id="div-' + image.id + '" class="gG2 mt5 p2">' 
				+ '<img src="' + Images.uploadedPath + image.name + '" width="' + image.width + '" height="' + image.height + '" class="dAAA xBottom"><br>'
				+ '<span class="f11 c666">www.mstaml.com' + Images.uploadedPath + image.name + '</span><br>'
				+ '<span id="num-' + image.id + '">' + Images.uploadedImagesCount + '</span>. التعليق: <input type="text" class="w300 xRight" maxlength="80" name="img-desc-' + image.id + '" value="' + Utils.EscapeHTML(image.description) + '"> '
				+ '<a class="button left w50" href="javascript:if(confirm(\'هل أنت متأكد من حذف الصورة؟\')){ Images.Remove(\'' + image.name + '\'); }" title="حذف الصورة">X</a>'
				+ '<a class="button left w50" href="javascript:Images.Move(\'' + image.id + '\', 1)" title="نقل للأسفل">&darr;</a>'
				+ '<a class="button left w50" href="javascript:Images.Move(\'' + image.id + '\', -1)" title="نقل للأعلى">&uarr;</a>'
				+ '<div class="clear"></div>'
			+ '</div>'
		);	
		Images.SetNotes();
		Images.SetImageVars();
		Utils.Log(image.size);
		Utils.Log(Images.uploadedImagesTotalSize);
	},

	"Move" : function(id, steps){
		var index, ids = [], item = -1, descriptions = {};
		for(index in Images.uploadedImages){
			ids[ids.length] = index;
			descriptions[index] = document.form['img-desc-' + index].value;
			if(index == id){ item = ids.length - 1; }
		}
		var other = item + steps;
		if(item >= 0 && other >= 0 && other <= (ids.length - 1)){
			var old = Images.uploadedImages, i = 0;
			Images.uploadedImages = {};
			Images.uploadedImagesCount = 0;
			Images.uploadedImagesTotalSize = 0;
			$('#uploadedImageList').empty();
			for(index in old){
				if(i == item){
					Images.AddImage(old[ids[other]]);
					document.form['img-desc-' + ids[other]].value = descriptions[ids[other]];
				}else if(i == other){
					Images.AddImage(old[ids[item]]);
					document.form['img-desc-' + ids[item]].value = descriptions[ids[item]];
				}else{
					Images.AddImage(old[ids[i]]);
					document.form['img-desc-' + ids[i]].value = descriptions[ids[i]];
				}
				++i;
			}
		}
	},
	
	"SetNotes" : function(){ // this will either delete the 'delete all' link or show it
		Utils.Log(Images.uploadedImagesCount);
		$('#uploadedImageNotes').empty();
		if(Images.uploadedImagesCount > 1){
			$('#uploadedImageNotes').append(
				'<br>يمكنك إعادة إظهار أي صورة أعلاه داخل النص أدناه، عن طريق نسخ ولصق رابطها في المكان الذي تريده داخل النص.<br>' + 
				'<a class="button left" href="javascript:if(confirm(\'هل أنت متأكد من أنك تريد حذف جميع الصور؟\')){Images.Remove(\'all\');}">حذف جميع الصور</a><div class="clear"></div>'
			);
		}
		if(Images.currentUploadIFrameDoc){
			Images.currentUploadIFrameDoc.uploadForm.image.disabled = Images.uploadedImagesCount >= Images.maxImageCount;
			Images.currentUploadIFrameDoc.getElementById('uploadDisabled').style.display = Images.uploadedImagesCount >= Images.maxImageCount ? 'inline' : 'none';
		}		
	},
	
	"SetImageVars" : function(){
		// generating the set images string
		var setImages = '';
		for(var index in Images.uploadedImages){
			setImages += Images.uploadedImages[index].name + ',';
		}
		// set the setImages hidden field
		document.form.setImages.value = setImages.substr(0, setImages.length - 1);
	},
	
	"GetProgress" : function (start, fileName, progressKey){ // this will get the progress from the server. it will start after the upload started
		fileName = unescape(fileName);
		progressKey = unescape(progressKey);
		Images.localFileNames[progressKey] = fileName;
		if(start){
			Images.AddProgressBar(fileName, progressKey);
			Images.AddUploadIFrame();
			setTimeout('Images.GetProgress(false, \'' + escape(fileName) + '\', \'' + escape(progressKey) + '\')', Images.progressInterval);
		}else{
			$.ajax({
				type: "GET",
				url: '/imageupload.php',
				dataType: "json",
				data: {
					"progressKey": progressKey,
					"rnd": Math.random()
				},
				success: function(response){
					Utils.Log(response);
					if(!response || response.cacheinfo || response.cancel_upload || response.error || response.total > Images.maxImageSize || response.saveDone){
						$('#progressTable-' + progressKey).remove();
						if(!response){
							alert(Images.msgErrorInternet + "\n(02)");
						}else if(response.cacheinfo){
							alert(Images.msgErrorInternet + "\n(03)");
						}else if(response.cancel_upload){
													}else if(response.error){
							alert(Images.msgErrorWrongImage + "\n(04)");
						}else if(response.total > Images.maxImageSize){
							Images.CancelUpload(progressKey);
							alert(Images.msgErrorWrongImage + "\n(05)");
						}else if($.type(response.saveDone) == 'object'){
							$("#iframe-" + progressKey).remove();
							Images.AddImage(response.saveDone);
						}else{
							alert(Images.msgErrorInternet + "\n(06)");
						}
					}else{
						var progressBar = document.getElementById('progressBar-' + progressKey);
						if(progressBar){ // update the progressBar if we didn't cancel the request
							var ratio = Math.round(response.progress * 100) + '%';
							progressBar.innerHTML = ratio;
							document.getElementById('progressTable-' + progressKey).title = 
								'السرعة: ' + Math.round(response.speed / 1000) + ' كيلوبايت في الثانية،' + 
								' الوقت المتبقي: ' + Math.round(response.remaining) + ' ثانية.';
							setTimeout('Images.GetProgress(false, \'' + escape(fileName) + '\', \'' + escape(progressKey) + '\')', Images.progressInterval);
						}
						Utils.Log({'progress' : response.progress, 'total' : response.total, 'ratio' : ratio, 'speed' : response.speed, 'remaining' : response.remaining});
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown){
					Images.CancelUpload(progressKey);
					alert(Images.msgErrorInternet + "\n(01)");
				}
			});
		}
	},
	
	"AddProgressBar" : function (fileName, progressKey){ // adding a progress bar for each upload when it start
		fileName = (fileName.split(/[\\/]/)).reverse()[0]; // get the local filename without path
		if(fileName.length > Images.fileNameMaxLength){
			fileName = fileName.substr(0, Images.fileNameMaxLength - 3) + '...';
		}
		$('#uploadProgressBars').append(
			'<table id="progressTable-' + progressKey + '" class="gG2"><tr>' + 
				'<td class="w30p ltr xLeft">' +
					fileName +
				'</td><td class="xCenter">' +
					'<img src="/images/uploading.gif" height="15" width="128" class="xMiddle"> <span id="progressBar-' + progressKey + '"></span>' +
				'</td><td class="w30p">' +
					'<a class="button right w50" href="javascript:Images.CancelUpload(\'' + progressKey + '\');" title="إلغاء">X</a><div class="clear"></div>' +
				'</td>' + 
			'</tr></table>'
		);
	},
	
	"AddUploadIFrame" : function (){ // this will add the upload iframe
		$('#uploadIFrames').contents().hide();
				var id = (new Date()).getTime() + '' + (100000 + Math.floor(Math.random() * 900000));
		$('#uploadIFrames').append('<iframe id="iframe-' + id + '" frameborder="0" border="0" scrolling="no" scrollbar="no" class="h23 w100p"></iframe>');
        var doc = document.getElementById('iframe-' + id).contentDocument;
        if(doc == undefined || doc == null){ // for ie
			doc = document.getElementById('iframe-' + id).contentWindow.document;
		}
        doc.open();
		doc.write(
			'<form name="uploadForm" id="uploadForm" action="/imageupload.php" method="post" enctype="multipart/form-data">' +
				'<input type="hidden" name="APC_UPLOAD_PROGRESS" value="' + id + '"/>' +
				'<input name="image" type="file" size="38"' +
					'onchange="' +
						'if(this.value){ ' +
							'window.parent.Images.GetProgress(true, this.value, \'' + id + '\'); ' +
							'document.getElementById(\'uploadForm\').submit(); }" ' +
					'onfocus="window.parent.Hint(this, true)" onblur="window.parent.Hint(this, false)" ' +
				'/>' +
				' <span id="uploadDisabled" style="font-size: 13px; font-family: Tahoma; color: red; font-weight: bold; display: none;">عفواً.. لا يمكنك إضافة المزيد!</span>' +
			'</form>'
		);
        doc.close();
		doc.body.style.margin = "0";
		doc.body.style.padding = "0";
		doc.body.style.direction = "rtl";
		doc.body.style.backgroundColor = "#F7F7F7"; // for ie6 only
		Images.currentUploadIFrameDoc = doc;
	},
	
	"CheckImages" : function(){ // validate the images when submitting the form
		if($('#uploadProgressBars').contents().size()){
			alert('عفواً.. لا يزال لديك صور لم يكتمل تحميلها بعد، يرجى انتظارها أولاً');
			return false;
		}
		if(Images.uploadedImagesCount > Images.maxImageCount){
			alert('عفواً.. يجب أن لا يزيد عدد الصور عن ' + Images.maxImageCount + ' صورة');
			return false;
		}
		if(Images.uploadedImagesTotalSize > Images.maxImageTotalSize){
			alert('عفواً.. يجب أن لا يزيد الحجم الكلي للصور عن ' + Math.floor(Images.maxImageTotalSize / 1000000) + ' ميقابايت، يرجى حذف بعض الصور');
			return false;
		}
		return true;
	},
	
	"CancelUpload" : function (progressKey){ // this will stop the uploading frame, and the server will disconnect automatically
		if(document.selection){ // ie
			document.getElementById('iframe-' + progressKey).contentWindow.document.execCommand('Stop');
		}else{
			document.getElementById('iframe-' + progressKey).contentWindow.stop();
		}
		$('#progressTable-' + progressKey).remove();
	},
	
	"Remove" : function(imageName){ // remove an image or all images
		for(var index in Images.uploadedImages){
			if(Images.uploadedImages[index].name == imageName || imageName == 'all'){
				$('#div-' + index).remove();
				Images.uploadedImagesCount -= 1;
				Images.uploadedImagesTotalSize -= parseInt(Images.uploadedImages[index].size);
				delete Images.uploadedImages[index];
				Images.SetNotes();
				Images.SetImageVars();
			}
		}
		Images.SetNumbers();
	}
}



var Stream = {
	"events" : null,
	"forum" : null,
	"updateInterval" : null,
	"timer" : null,
	"updateInProgress": null,
	"delay" : null,
	"lastItemID" : null,
	"lastThreadID" : null,
		"msgErrorInternet" : "عفواً.. حصل خطأ في الاتصال بالإنترنت، يرجى إعادة تحميل الصفحة أو مراسلتنا!!!",
	"msgErrorNoUpdate" : "أخي الكريم، إذا أردت أن يتم تحديث الصفحة بشكل تلقائي، فيجب أن تسجل الدخول إلى عضوية في موقع مستعمل.",
	
	"Init" : function(){
		if(Stream.updateInterval){
			var d = new Date();
			Stream.lastUpdate = d.getTime();
			Stream.delay = Stream.CalculateDelay();
			Stream.timer = window.setTimeout(Stream.WriteReply, Stream.CalculateDelay);
		}
	},
	
	"CalculateDelay" : function(){
		if(Stream.events.length >= Stream.updateInterval){ // too much busy
			return 1000;
		}else if(Stream.events.length == 0){ // no traffic at all
			return Stream.updateInterval * 1000;
		}else{
			return (Stream.updateInterval / Stream.events.length) * 1000; // normal traffic
		}
	},
	
	"WriteReply" : function(){
		if(!Stream.events.length){
			Stream.Update();
		}else{
			console.log(Stream.events.length);
			var item = Stream.events.shift();
			var icon = 
				(Stream.forum ?
						(item.writer != "0" ? ' writer_gif' : '') :
						(item.known != "0" ? 
							' known_gif': 
							(item.special != "0" ? ' favo_gif' : ''))) ;
			$('#streamBox').append(
					'<div>'
						+ '<span class="sprite' + icon + '" ' + (icon ? '' : 'style="background-position  : 500px 500px;"') + '></span>'
						+ '<a href="' + (Stream.forum ? '/forum/fr.php?i=' : '/section/item.php?i=') + item.id + '">' + Utils.EscapeHTML(item.title) + '</a><br>'
						+ (item.threadID ? Utils.nl2br(Utils.EscapeHTML(item.body)) : '')
						+ '</div><hr>');
			if(item.threadID){
				Stream.lastThreadID = item.threadID;
			}else{
				Stream.lastItemID = item.id;
			}
			Stream.timer = window.setTimeout(Stream.WriteReply, Stream.delay);
		}
	},
	
	"Update" : function(){
		Utils.Log('updateStream')
		if(Stream.updateInProgress){
			Utils.Log('inProgress');
			Stream.timer = window.setTimeout(Stream.WriteReply, Stream.delay);
			return;
		}
		var d = new Date();
		if(d.getTime() > Stream.lastUpdate + (Stream.updateInterval * 1000)){
			Stream.updateInProgress = true;
			var streamData = {};
			streamData.f = Stream.forum;
			streamData.ajax = 1;
			if(Stream.lastItemID){ streamData.lastItemID = Stream.lastItemID; }
			if(Stream.lastThreadID){ streamData.lastThreadID = Stream.lastThreadID; }
			streamData.rnd = Math.random();
			$.ajax({
				type: "GET",
				url: '/stream.php',
				dataType: "json",
				data: streamData,
				success: function(response){
					Utils.Dir(response);
					if(!response){
						alert(Stream.msgErrorInternet + "\n(02)");
					}else if(response.noUpdate){
						alert(Stream.msgErrorNoUpdate + "\n(03)");
					}else{
						var d = new Date();
						Stream.lastUpdate = d.getTime();
						Stream.events = response;
						Stream.delay = Stream.CalculateDelay();
						Stream.updateInProgress = null;
						Stream.WriteReply();
						Stream.timer = window.setTimeout(Stream.WriteReply, Stream.delay);
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown){
					alert(StreamImages.msgErrorInternet + "\n(01)");
				}
			});
		}else{
			Stream.timer = window.setTimeout(Stream.WriteReply, Stream.delay);
		}
	}
}	
		
		
		
var Utils = {
	"EscapeHTML" : function (text){ // used for escaping desccriptions
		return ('' + (text == null ? '' : text)).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quote;");
	},

	"ArrayIndexOf" : function(a, o){ // this is for IE missing indexOf function available for Firefox
		if(Array.indexOf){
			return a.indexOf(o);
		}else{
			for(var i = 0; i < a.length; i++){
				if(a[i] === o){ return i; }
			}
			return -1;
		}
	},

	"Log" : function(data){
		if(consoleDebug && console && console.log){
			console.log(data);
		}
	},

	"Dir" : function(data){
		if(consoleDebug && console && console.dir){
			console.dir(data);
		}
	},
	
	"ParseQuery" : function(qs){ // this will take full url and return an object with var names and last value
		var params = {};
		jQuery.each(qs.match(/\?(.*)$/)[1].split('&'), function(i, p){
			p = p.split('=');
			params[p[0]] = unescape(p[1]).replace(/\+/g,' ');
		});
		return params;
	},
	
	"Trim" : function (string){
		return ('' + string).replace(/^\s+|\s+$/g, "");
	},

	"nl2br" : function(string){
		return ('' + string).replace(/(\r\n|\n\r|\n|\r)/g, "<br>$1");
	},

	"FindObjectInArray" : function (arrayOfObjects, criteriaObject, startFrom){
		Utils.Dir(criteriaObject);
		startFrom = startFrom ? startFrom : 0;
		for(var i = startFrom; i < arrayOfObjects.length; ++i){
			var criteria = 1;
			for(var index in criteriaObject){
				if(arrayOfObjects[i][index] != criteriaObject[index]){ 
					criteria = 0; 
				}
			}
			if(criteria){ return i; }
		}
		return -1;
	}

}
/*</script>*/
