/*
 * SimpleModal 1.1.1 - jQuery Plugin
 * http://www.ericmmartin.com/projects/simplemodal/
 * http://plugins.jquery.com/project/SimpleModal
 * http://code.google.com/p/simplemodal/
 * all
 * Copyright (c) 2007 Eric Martin - http://ericmmartin.com
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Revision: $Id: jquery.simplemodal.js 93 2008-01-15 16:14:20Z emartin24 $
 */
var mStatus,url,urlCall,dataCall,data,callBack,errorCall,successMessage,closeBtn,closeModal=function(){return false;};var baytModal = new ajaxModal();

$('#globalMW').ready(function() {
	$('#globalMWCancel').click(function() { closeModal();});
});

function ajaxModal(){
	this.setModal = function (title, content, show_ok, onClose, longin_info) {
		if($("#globalMW").length == 0){
			return false;
		} else {
			showOk = show_ok;
			if (onClose) { 
				closeModal=onClose
			} else {
				closeModal = function () { $.modal.close(true);	}
			} 
			(show_ok)?$("#globalMWOk").removeClass():$("#globalMWOk").addClass("hide");
			$("#globalMWTitle").html(title);
			$("#globalMWContent").html(content);
			if ( longin_info != null ) {
				$("#globalMWButtons").removeClass("bttns");
				$("#globalMWButtons").addClass("r");
				$("#globalMWButtons").css("width","67%");
				$("#globalMWLonginInfo").html(longin_info);
			} else {
				$("#globalMWLonginInfo").addClass("hide");
			}
			if (showOk) { 
				show_hide_loading(false);
				$("#globalMW").modal({close: (true), onClose: function () {closeModal();}}); 
			}
		}
	};
	
	this.setDeleteModal = function (onClose) {
		if($("#globalMW").length == 0){
			return false;
		} else {
			showOk = true;
			if (onClose) { 
				closeModal=onClose
			} else {
				closeModal = function () { $.modal.close(true);	}
			} 
			$("#globalMWOk").removeClass(); 
			$("#globalMWTitle").html(delTitle);
			$("#globalMWContent").html(delBody);
			show_hide_loading(false);
			$("#globalMW").modal({close: (true)});
		}
	};

	this.postData = function (urlCallVal,dataCallVal,callBackVal,errorCallVal,successMessageVal,mStatusVal,closeBtnText){ 
		urlCall=urlCallVal;
		dataCall=dataCallVal;
		callBack=callBackVal;
		errorCall=errorCallVal;
		
		closeBtn = (closeBtnText) ? closeBtnText : ''
		if ( mStatusVal == 0 ) 
			mStatus = mStatusVal;
		 else 
			mStatus = 1;
		
		if (successMessageVal) 
			successMessage=successMessageVal;
		else 
			successMessage="" ;
		if(!showOk) { 
			postDataCode ();
		}
	};
}

function postDataCode() {
	(jQuery.isFunction(dataCall))?data = dataCall():data = dataCall;
	(jQuery.isFunction(urlCall))?url = urlCall():url = urlCall;
	$.baytMW(url,data,callBack,errorCall);
}	

function validateModal(form) {
	if(formValidator(form)) {
		$("#submit-alert-message").removeClass();
		$("#submit-alert-message").addClass("hide"); postDataCode();
	} else {
		$("#submit-alert-message").removeClass();
		$("#submit-alert-message").addClass("alert");
	} 
	return false;
}

function show_hide_loading(show_p) {
	(show_p)?$("#modalloading").modal():$.modal.impl.close(true);
}

jQuery.extend({
	bayt: function(url,data,callback,errorCallback,type) {
		if(jQuery.isFunction(data)) {
			callback=data; data={};
		}
		return jQuery.ajax({
			beforeSend: function(xhr){
				xhr.setRequestHeader("Accept","text/x-json");
				if (mStatus) {
					$.modal.close(true);
					show_hide_loading(true);
				}
			},
			timeout: 60000,
			type: "POST",
			url: url,
			data: data,
			success: callback,
			error: errorCallback,
			dataType: type
		});
	},
	
	baytMW: function(url,data,callback,errorCallBack,type) {
		$.bayt(	url,
			data,
			function (data,status){
				show_hide_loading(false);
				if(successMessage) { 
					$('#globalMW').modal({close: (false)});
					$('#globalMWMessage').html(successMessage);
					if (closeBtn != '') 
						$('#globalMWCancel').text(closeBtn);
				}
				if(jQuery.isFunction(callback)){callback(data,status);}
			},
			function(xhr,errorType){
				show_hide_loading(false);
				if ( errorType == "timeout" ) {
					/* Timeout Error */
					var responseText = ($('body').attr('id') == "ar") ? "<strong>خطأ:</strong> يوجد خطأ ما، آسفون لإزعاجكم" : "<strong>Error:</strong> Sorry an error occurred."
					$('#globalMW').modal({close: (true)});
					$('#globalMWError').html('<p class=\"alert\">'+responseText+'</p>');
					$('#globalMWOk').text(retryBtn);
					if(jQuery.isFunction(errorCallBack)){errorCallBack();}
				} else if( xhr.status == 401){
					(bccHasLoginModal)?loginPopupModal():window.location = loginURL;
				} else {
					$('#globalMW').modal({close: (true)});
					$('#globalMWError').html(xhr.responseText);
					$('#globalMWOk').text(retryBtn);
					if(jQuery.isFunction(errorCallBack)){errorCallBack();}
				}
			},
			type
		);
	}
});

jQuery.fn.extend({
	scrollTo : function(speed, easing) {
		    return this.each(function() {
		      $('html,body').animate({scrollTop: $(this).offset().top}, speed, easing);
		    });
		  },
	delay :function(time,func) { 
		 	 return this.each(function(){
				setTimeout(func,time);
			});
		}
		  
});

var body_loaded_p = true;
if($.browser.msie&&($.browser.version<8)){body_loaded_p=false;jQuery('body').ready(function(){body_loaded_p=true});}

(function($){$.modal=function(data,options){return $.modal.impl.init(data,options);};$.modal.close=function(){$.modal.impl.close(true);};$.fn.modal=function(options){return $.modal.impl.init(this,options);};$.modal.defaults={overlay:50,overlayId:'modaloverlay',overlayCss:{},containerId:'modalpopup',containerCss:{},close:false,closeTitle:'Close',closeClass:'modalClose',persist:false,onOpen:null,onShow:null,onClose:null};$.modal.impl={opts:null,dialog:{},init:function(data,options){if(body_loaded_p==true){if(this.dialog.data){return false;}this.opts=$.extend({},$.modal.defaults,options);if(typeof data=='object'){data=data instanceof jQuery?data:$(data);if(data.parent().parent().size()>0){this.dialog.parentNode=data.parent();if(!this.opts.persist){this.dialog.original=data.clone(true);}}}else if(typeof data=='string'||typeof data=='number'){data=$('<div>').html(data);}else{if(console){console.log('SimpleModal Error: Unsupported data type: '+typeof data);}return false;}this.dialog.data=data.addClass('modalData');data=null;this.create();this.open();if($.isFunction(this.opts.onShow)){this.opts.onShow.apply(this,[this.dialog]);}return this; } else {return this;} },create:function(){this.dialog.overlay=$('<div>').attr('id',this.opts.overlayId).addClass('modaloverlay').css($.extend(this.opts.overlayCss,{opacity:this.opts.overlay/100,height:'100%',width:'100%',position:'fixed',left:0,top:0,zIndex:3000})).hide().appendTo('body');this.dialog.container=$('<div>').attr('id',this.opts.containerId).addClass('modalpopup').css($.extend(this.opts.containerCss,{position:'fixed',zIndex:3100})).append(this.opts.close?'<a class="modalcloseimg '+this.opts.closeClass
+'" title="'+this.opts.closeTitle+'"></a>':'').hide().appendTo('body');if($.browser.msie&&($.browser.version<7)){this.fixIE();}this.dialog.container.append(this.dialog.data.hide());},bindEvents:function(){var modal=this;$('.'+this.opts.closeClass).click(function(e){e.preventDefault();modal.close();});},unbindEvents:function(){$('.'+this.opts.closeClass).unbind('click');},fixIE:function(){var wHeight=$(document.body).height()+'px';var wWidth=$(document.body).width()+'px';this.dialog.overlay.css({position:'absolute',height:wHeight,width:wWidth});this.dialog.container.css({position:'absolute'});this.dialog.iframe=$('<iframe src="javascript:false;">').css($.extend(this.opts.iframeCss,{opacity:0,position:'absolute',height:wHeight,width:wWidth,zIndex:1000,width:'100%',top:0,left:0})).hide().appendTo('body');},open:function(){if(this.dialog.iframe){this.dialog.iframe.show();}if($.isFunction(this.opts.onOpen)){this.opts.onOpen.apply(this,[this.dialog]);}else{this.dialog.overlay.show();this.dialog.container.show();this.dialog.data.show();}this.bindEvents();},close:function(external){if(!this.dialog.data){return false;}if($.isFunction(this.opts.onClose)&&!external){this.opts.onClose.apply(this,[this.dialog]);}else{if(this.dialog.parentNode){if(this.opts.persist){this.dialog.data.hide().appendTo(this.dialog.parentNode);}else{this.dialog.data.remove();this.dialog.original.appendTo(this.dialog.parentNode);}}else{this.dialog.data.remove();}this.dialog.container.remove();this.dialog.overlay.remove();if(this.dialog.iframe){this.dialog.iframe.remove();}this.dialog={};}this.unbindEvents();}};})(jQuery);
/*
 * Close the pop up modal when user press 'Esc' on keyboard
 */
$(document).keydown(function(e){if(e == null){/*IE*/keycode = event.keyCode;}else{/*mozilla*/keycode = e.which;}if(keycode == 27){/*close*/closeModal();}}); 
 
/*
 * Multiple Select 
 */
 
function addSelect( fieldName ,max ,otherFieldName){
	var numOfSelect = 1;
	while ( $('#id-'+fieldName+'_'+numOfSelect).html() != null ) {numOfSelect++;}
	var fieldID;
	if ( max >= numOfSelect ) {
		BuildSelect( $('#id-'+fieldName+'_1').html() , fieldName , max , numOfSelect, otherFieldName);
	} else {
		for ( var i = 1 ; i <= max ; i++ ) {
			fieldID=(otherFieldName!=null)?fieldName+'_'+i:'id-'+fieldName+'_'+i
			var class_hide = $('#'+fieldID).attr('className');	
			if (class_hide == "hide" ) {
				$('#'+fieldID).show();
				$('#'+fieldID).attr('className','');
				$('#rem-'+fieldName+'_'+i+'-select').show();
				$('#rem-'+fieldName+'_'+i+'-select').attr('className','');
				$('#add-'+fieldName+'-select').show();			
				break
			} 
		}
		for ( var i = 1 ; i <= max ; i++ ) {
			fieldID=(otherFieldName!=null)?fieldName+'_'+i:'id-'+fieldName+'_'+i
			var class_hide = $('#'+fieldID).attr('className');
			if ( class_hide == "hide" ) {
				$('#add-'+fieldName+'-select').show();
				break
			} else {
				$('#add-'+fieldName+'-select').hide();
			}
		}
	}
}

function removeSelect( fieldName , i , max, otherFieldName) {
	var class_hide = $('#id-'+fieldName+'_'+i).attr('className');
	if ( class_hide !=null ) {
		if(otherFieldName!=null) {
			$('#'+fieldName+'_'+i).attr('className','hide');
			$('#'+fieldName+'_'+i).hide();
			// CLEAR THE SELECTED VALUE
			// FIREFOX
			$("#id-"+otherFieldName+"_"+i+" option:selected")[0].defaultSelected = false;
			// IE
			$("#id-"+otherFieldName+"_"+i).val("");
		} else {
			$('#id-'+fieldName+'_'+i).attr('className','hide');
			$('#id-'+fieldName+'_'+i).hide();
			$('#rem-'+fieldName+'_'+i+'-select').attr('className','hide');
			$('#rem-'+fieldName+'_'+i+'-select').hide();
		}
		// CLEAR THE SELECTED VALUE
		// FIREFOX
		$("#id-"+fieldName+"_"+i+" option:selected")[0].defaultSelected = false;
		// IE
		$("#id-"+fieldName+"_"+i).val("");
		$('#add-'+fieldName+'-select').show();
	}
	for ( var i = max ; i > 1 ; i-- ) {
		var class_hide = $('#id-'+fieldName+'_'+i).attr('className');
		if ( class_hide =="hide" ) {$('#add-'+fieldName+'-select').show();}
	}
	var numOfSelect = 1;
	while ( $('#id-'+fieldName+'_'+numOfSelect).html() != null ) {numOfSelect++;}
	if ( max != numOfSelect ) {$('#add-'+fieldName+'-select').show();}
	getMultiValues (fieldName ,max ,numOfSelect, otherFieldName)
} 

function getMultiValues (fieldName ,max , numOfSelect, otherFieldName) {
	var values = "";
	for ( var i = 1 ; i <= max ; i++ ) {
		var class_hide = (otherFieldName!=null) ? $('#'+fieldName+'_'+i).attr('className') : $('#id-'+fieldName+'_'+i).attr('className');
		if ( $('#id-'+fieldName+'_'+i).val() != '' && $('#id-'+fieldName+'_'+i).html() != null && class_hide != "hide" ) {
			if (otherFieldName!=null) {
				var otherFieldValue = 0;
				if ($('#id-'+otherFieldName+'_'+i).val() != '' && $('#id-'+otherFieldName+'_'+i).html() != null) {
					otherFieldValue = $('#id-'+otherFieldName+'_'+i).val();
				}
				values = values + $('#id-'+fieldName+'_'+i).val() + "," + otherFieldValue + " ";
			} else {
				values = values + $('#id-'+fieldName+'_'+i).val() + " ";	
			}
		}
	}
	$("input[name="+fieldName+"]").val(values);
}

function BuildSelect( inhtml , fieldName , max , numOfSelect, otherFieldName)
{
	var newSelectCoded = '<select onchange="javascript:getMultiValues(\''+fieldName+'\', \''+max+'\',\''+numOfSelect+'\');" id="id-'+fieldName+'_'+numOfSelect+'" name="'+fieldName+'_'+numOfSelect+'">'+inhtml+'</select>';
	var removeLink = ' <a id="rem-'+fieldName+'_'+numOfSelect+'-select" class="" href = "javascript:removeSelect(\''+fieldName+'\',\''+numOfSelect+'\',\''+max+'\');" ><img src="/images/icons/blt-close.gif" alt="x" /></a>';
	if(otherFieldName!=null) {
		var otherInhtml = $('#id-'+otherFieldName+'_1').html();
		newSelectCoded = '<span id="'+fieldName+'_'+numOfSelect+'" style="display:block;"><select onchange="javascript:getMultiValues(\''+fieldName+'\', \''+max+'\',\''+numOfSelect+'\',\''+otherFieldName+'\');" class="w1" id="id-'+fieldName+'_'+numOfSelect+'" name="'+fieldName+'_'+numOfSelect+'">'+inhtml+'</select>';
		newSelectCoded = newSelectCoded + ' <select onchange="javascript:getMultiValues(\''+fieldName+'\', \''+max+'\',\''+numOfSelect+'\',\''+otherFieldName+'\');"class="w1" id="id-'+otherFieldName+'_'+numOfSelect+'" name="'+otherFieldName+'_'+numOfSelect+'">'+otherInhtml+'</select>';
		removeLink = ' <a id="rem-'+fieldName+'_'+numOfSelect+'-select" class="" href = "javascript:removeSelect(\''+fieldName+'\',\''+numOfSelect+'\',\''+max+'\',\''+otherFieldName+'\');" ><img src="/images/icons/blt-close.gif" alt="x" /></a></span>';
	}
	
	$('#multi-'+fieldName+'-select').before(newSelectCoded+removeLink); 
	//	$('#multi-'+fieldName+'-select').before(removeLink);
	$("select[name="+fieldName+"_"+numOfSelect+"] option[value='']").attr("selected","selected");
	$("select[name="+otherFieldName+"_"+numOfSelect+"] option[value='']").attr("selected","selected");
	var numOfSelect = 1;
	var fieldID=(otherFieldName==null)?'id-'+fieldName+'_'+numOfSelect:fieldName+'_'+numOfSelect;
	while ( $('#'+fieldID).html() != null ) {
		var class_hide = $('#'+fieldID).attr('className');
		if ( class_hide == "hide" ) {
			$('#add-'+fieldName+'-select').show();
			break
		} else if (max == numOfSelect) {$('#add-'+fieldName+'-select').hide();}
		numOfSelect++;
		fieldID=(otherFieldName==null)?'id-'+fieldName+'_'+numOfSelect:fieldName+'_'+numOfSelect;
	}
}

function clearMultiSelect( fieldName , max, otherFieldName )
{
	var form_element = $('*[name='+fieldName+']');
	var selected_values = $(form_element).val().split(" ")
	for (i=2 ; i<= max ; i++) {
		removeSelect( fieldName , i ,max, otherFieldName);	
	}
	$("#id-"+fieldName+"_1 option:selected")[0].defaultSelected = false;
	$("#id-"+fieldName+"_1").val("");
	if( otherFieldName != null ) {
		//CLEAR THE SELECTED VALUE
		// FIREFOX
		$("#id-"+otherFieldName+"_1 option:selected")[0].defaultSelected = false;
		// IE
		$("#id-"+otherFieldName+"_1").val("");
	}
	form_element.val("");
}


(function($)
{
/*
* This function accepts the iso value passed by the element where this function was used.
* USAGE:
* OPTIONAL values:
* lst_cities_container: city dropdown container
* opt_cities: city dropdown element id
* selected_city: selected city for a country
* $(element).get_cities_per_country({"lst_cities_container":"#div_job_company_city", 
*                                    "opt_cities":"#id-job_company_city",
                                     "selected_city":obj.job_country_iso_city}).focus();
* After calling get_cities_per_country, attached a valid event for this 'SELECT' element.
* Afterwhich, all the bind controls can be executable on this element. 
*
*
*/
    $.fn.get_cities_per_country = function(options) {
        return this.each(function(){
            $(this).unbind('focus').bind('focus', function(e){
                $(this).display_city_option({'iso':$(this).val(), 'options':options});
            });
            $(this).unbind('change').bind('change', function(e){
                $(this).unbind('focus');
                options.selected_city =  '';
                $(this).display_city_option({'iso':$(this).val(), 'options':options});          
            });
        })
    
    };
    /*Display the cities if present and toggles the city list container to diplay the options*/
    $.fn.display_city_option =  function(o) {
        /*allow to extend or add new object defaults*/
        var opts = $.extend(jQuery.fn.get_cities_per_country.defaults, o.options); 
        var c_iso = o.iso
        if (c_iso != "") {
            $.getJSON(opts.url_iso_cty,{byt_reg_stage:25,country_iso:c_iso}, function(json){
		 	    var sel_opts = '';
		 		if ( json.length > 0 ) {
			 		sel_opts += '<option value="" selected="selected">- Select one -</option>';
      				for (var i = 0; i < json.length; i++) {
						sel_opts += '<option value="' + json[i].optionValue + '">' + json[i].optionDisplay + '</option>';
					}	      				
      				sel_opts += '<option value="'+ c_iso + ',0,0">Other</option>';
      				$(opts.opt_cities).html(sel_opts);
      				$(opts.opt_cities + ' option[value=' + opts.selected_city+']').attr('selected','selected');
					$(this).toggle_city_option(1);
		 		} else {
					$(opts.opt_cities).html(sel_opts);
					$(this).toggle_city_option(0);
		 		}
            });			 	
        } else {
            $(this).toggle_city_option(0);
            $(opts.opt_cities).html("");
        }    
    }
    /*Toggles the city list container*/
    $.fn.toggle_city_option = function(flag) {
        var opts = $(this).get_cities_per_country.defaults;
        if (opts.lst_cities_container != undefined && opts.opt_cities != undefined) {
            if (flag) {
                $(opts.lst_cities_container).attr('className','req');
                $(opts.opt_cities).attr('className','req');
                $(opts.lst_cities_container).show();
            } else {
                $(opts.lst_cities_container).hide();
                $(opts.opt_cities).removeClass();
            }
        }
    }  
    /*default values*/  
    $.fn.get_cities_per_country.defaults = {url_iso_cty: '/app/control/byt_reg_manager.tcl',additional_params: ''};
})(jQuery);