function getHTTPObject() {
	var http = false;
	//Use IE's ActiveX items to load the file.
	if(typeof ActiveXObject != 'undefined') {
		try {http = new ActiveXObject("Msxml2.XMLHTTP");}
		catch (e) {
			try {http = new ActiveXObject("Microsoft.XMLHTTP");}
			catch (E) {http = false;}
		}
	//If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document.
	} else if (XMLHttpRequest) {
		try {http = new XMLHttpRequest();}
		catch (e) {http = false;}
	}
	return http;
}
function xpos(obj){
	var curleft = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}else if (obj.x)
		curleft += obj.x;
	return curleft;
}
function ypos(obj){
	var curtop = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}else if (obj.y)
		curtop += obj.y;
	return curtop;
}
function showHide(element, value){
	element = $(element);
    if(value == 1){
		element.style.display = 'block';
		// close overlay if user clicks shadow overlay
		$('overlay').onclick = function() { closeBox('box'); }
	}else{
		element.style.display = 'none';
		$('overlay').onclick = null;
	}
}

function box(action, id, vars, pos){
	var params, url;
	switch(action){
		case 'add':
			url = 'shift_add.php';
			params = 'url='+url+'&vars='+vars;
		break;
		case 'edit':
			url = 'shift_edit.php';
			params = 'url='+url+'&shiftId='+id+'&vars='+vars;
		break;
		case 'delete':
			url = 'shift_delete.php';
			params = 'url='+url+'&shiftId='+id+'&vars='+vars;
		break;
		case 'add_person':
			url = 'person_add.php';
			params = 'url='+url+'&employeeId='+id+'&vars='+vars;
		break;
		case 'edit_person':
			url = 'person_edit.php';
			params = 'url='+url+'&employeeId='+id+'&vars='+vars;
		break;
		case 'delete_person':
			url = 'person_delete.php';
			params = 'url='+url+'&employeeId='+id+'&vars='+vars;
		break;
		case 'edit_location':
			url = 'location_edit.php';
			params = 'url='+url+'&id='+id;
		break;
		case 'delete_location':
			url = 'location_delete.php';
			params = 'url='+url+'&id='+id;
		break;
		case 'swap_shift':
			url = 'swap_shift.php';
			params = 'url='+url+'&vars='+vars;
		break;
		default:
			url = null;
	}
	if(url != null){
		// get html from mod file
		var http = getHTTPObject();
		http.open("POST", "/mods/ajax_manager.php", true);
		
		//Send the proper header infomation along with the request
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http.setRequestHeader("Content-length", params.length);
		http.setRequestHeader("Connection", "close");
		
		http.onreadystatechange = function(){
			if(http.readyState == 4){
				$('contents').innerHTML = http.responseText;
				$('box').style.visibility = 'hidden';
				$('box').style.display = 'block';
				
				// box position
				// inner window width
				var docWidth = self.screen.availWidth;
				var width = getElementWidth('box');
				var height = getElementHeight('box');
				var top = pos.y + 25;
				var left = (pos.x-width)+5;
				
				if(left < 0){
					left = pos.x-10;
					$('arrow').src = '/images/left_arrow.png';
					$('arrow').setAttribute('style','position: absolute; top: -17px; left: 0; margin-left: 15px;');
				}else{
					$('arrow').src = '/images/right_arrow.png';
					$('arrow').setAttribute('style','position: absolute; top: -17px; right: 0;');
				}
				$('box').style.top = top + 'px';
				$('box').style.left = left + 'px';
				
				showHide('overlay', 1);
				$('box').style.visibility = 'visible';
			}
		}
		http.send(params);
	}
}
function closeBox(id){
	$(id).style.display = 'none';
	showHide('overlay', 0);
}

function shiftManager(action, id, vars){
	// shift collision
	var success;
	if(action == 'add' || action == 'edit'){
		var shift_check = check_shift_collision(vars[0],vars[1],vars[2]);
		if(shift_check == true){
			$('box_error').innerHTML = 'Shift collision detected.';
			$('box_error').style.display = 'block';
			success = false;
		}else{
			closeBox('box');
			success = true;
		}
	}
	if(action == 'delete'){
		closeBox('box');
		success = true;
	}
	if(success == true){
		var http = getHTTPObject();
		if(vars != null){
			var params = 'action='+action+'&id='+id+'&vars='+vars;
			var array_len = vars.length;
			var page = vars[array_len-1];
		}else{
			var params = 'action='+action+'&id='+id;
		}
		
		http.open("POST", "/includes/shift_manager.php", true);
		
		//Send the proper header infomation along with the request
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http.setRequestHeader("Content-length", params.length);
		http.setRequestHeader("Connection", "close");
		
		http.onreadystatechange = function(){
			switch(http.readyState){
				case 4:
					if(http.status == 200){
						switch(action){
							case 'add':
								// add shift
								if(page == 'dayPage'){
									$('shifts').innerHTML = http.responseText;
								}else{
									window.location = '/day/' + http.responseText + '/';
								}
							break;
							case 'edit':
								// update current row
								$('shift_' + id).innerHTML = http.responseText;
							break;
							default:
								// update all rows
								$('shifts').innerHTML = http.responseText;
						}
					}else{
						$('shifts').innerHTML = '<tr><td colspan="3">An error occurred</td></tr>';
					}
				break;
				case 1:
					switch(action){
						case 'add':
							$('submitButton').innerHTML = '<img src="/images/loading.gif" alt="Loading&hellip;" />';
						break;
						case 'edit':
							$('shift_' + id).innerHTML = '<td colspan="3" align="center"><img src="/images/loading.gif" alt="Loading&hellip;" /></td>';
						break;
						case 'delete':
							//
						break;
					}
				break;
			}
		}
		http.send(params);
	}
}

function personManager(action, id, vars){
	closeBox('box');
	var http = getHTTPObject();
	if(vars != null){
		var params = 'action='+action+'&id='+id+'&vars='+vars;
		if(vars[2] > 1){
			var outputId = 'executives';
		}else{
			var outputId = 'employees';
		}
	}else{
		var params = 'action='+action+'&id='+id;
	}
	
	http.open("POST", "/includes/person_manager.php", true);
	
	//Send the proper header infomation along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	
	http.onreadystatechange = function(){
		switch(http.readyState){
			case 4:
				if(http.status == 200){
					switch(action){
						case 'edit':
							// update current row
							$('employee_' + id).innerHTML = http.responseText;
							notify('Update successfull');
						break;
						default:
							// for add and delete actions
							// update all rows
							var temp_vars = http.responseText.split('__');
							var level = temp_vars[0];
							var text = temp_vars[1];
							
							if(level > 1){
								var outputId = 'executives';
							}else{
								var outputId = 'employees';
							}
							
							$(outputId).innerHTML = text;
							
							if(action == 'add'){
								notify('New person added');
							}else{
								notify('Person was deleted');
							}
					}
				}else{
					$(outputId).innerHTML = '<tr><td colspan="3">An error occurred</td></tr>';
				}
			break;
			case 1:
				switch(action){
					case 'add':
						$('submitButton').innerHTML = '<img src="/images/loading.gif" alt="Loading&hellip;" />';
					break;
					case 'edit':
						$('employee_' + id).innerHTML = '<td colspan="3" align="center"><img src="/images/loading.gif" alt="Loading&hellip;" /></td>';
					break;
					case 'delete':
						//
					break;
				}
			break;
		}
	}
	http.send(params);
}

function locationManager(action, id, vars){
	closeBox('box');
	var http = getHTTPObject();
	if(vars != null){
		var params = 'action='+action+'&id='+id+'&vars='+vars;
	}else{
		var params = 'action='+action+'&id='+id;
	}
	
	http.open("POST", "/includes/location_manager.php", true);
	
	//Send the proper header infomation along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	
	http.onreadystatechange = function(){
		switch(http.readyState){
			case 4:
				if(http.status == 200){
					switch(action){
						case 'edit':
							// update current row
							$('location_' + id).innerHTML = http.responseText;
						break;
						default:
							// update all rows
							$('locations').innerHTML = http.responseText;
							new Effect.Opacity('locations_error', {delay:6.0,duration:0.5, from:1.0, to:0.0,afterFinish: clearObject});
					}
				}else{
					$('locations').innerHTML = '<tr><td colspan="3">An error occurred</td></tr>';
				}
			break;
			case 1:
				switch(action){
					case 'add':
						$('submitButton').innerHTML = '<img src="/images/loading.gif" alt="Loading&hellip;" />';
					break;
					case 'edit':
						$('location_' + id).innerHTML = '<td colspan="3" align="center"><img src="/images/loading.gif" alt="Loading&hellip;" /></td>';
					break;
					default:
						//
				}
			break;
		}
	}
	http.send(params);
}
function swap(shiftId){
	window.location = '/request/shift-change/'+shiftId+'/';
}
function drop(shiftId){
	window.location = '/request/drop-shift/'+shiftId+'/';
}

function updateWeek(id, year, month, numWeeks){
	window.location = '/profile/'+id+'/'+numWeeks+'/'+year+'/'+month+'/';
}
function check_user(user){
	var http = getHTTPObject();
	var params = 'action=username&user=' + user;
	
	http.open("POST", "/includes/form_checks.php", true);
	
	//Send the proper header infomation along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	
	http.onreadystatechange = function(){
		switch(http.readyState){
			case 4:
				if(http.status == 200){
					if(http.responseText == 'true'){
						$('user_check').innerHTML = '| Email is taken. Try another.';
					}else{
						$('user_check').innerHTML = '';
					}
				}else{
					$('user_check').innerHTML = 'Error occured while checking email.';
				}
			break;
			case 1:
				$('user_check').innerHTML = 'Checking&hellip;';
			break;
		}
	}
	http.send(params);
}
function check_company(name){
	var http = getHTTPObject();
	var params = 'action=company&name=' + name;
	
	http.open("POST", "/includes/form_checks.php", true);
	
	//Send the proper header infomation along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	
	http.onreadystatechange = function(){
		switch(http.readyState){
			case 4:
				if(http.status == 200){
					if(http.responseText == 'true'){
						$('company_check').innerHTML = 'Company name is taken. Try another.';
					}else{
						$('company_check').innerHTML = '';
						// filter company name for use as URL
						var newURL = name.replace(/\s/g, "");
						newURL = newURL.toLowerCase();
						$('url').value = newURL;
						if(newURL == '') newURL = 'example';
						$('review_url').innerHTML = 'http://' + newURL + '.skedual.com';
					}
				}else{
					$('company_check').innerHTML = 'Error occured while checking company name.';
				}
			break;
			case 1:
				$('company_check').innerHTML = 'Checking&hellip;';
			break;
		}
	}
	http.send(params);
}
function check_shift_collision(employee_id, start_time, end_time){
	var http = getHTTPObject();
	var params = 'action=shift&employee_id=' + employee_id + '&start_time=' + start_time + '&end_time=' + end_time;
	
	http.open("POST", "/includes/form_checks.php", true);
	
	//Send the proper header infomation along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	
	http.onreadystatechange = function(){
		switch(http.readyState){
			case 4:
				return http.responseText;
			break;
		}
	}
	http.send(params);
}
function request(type,vars){
	closeBox('box');
	var http = getHTTPObject();
	var params = 'action='+type+'&vars=' + vars;	
	http.open("POST", "/includes/request_manager.php", true);
	
	//Send the proper header infomation along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	
	http.onreadystatechange = function(){
		switch(http.readyState){
			case 4:
				if(http.status == 200){
					// split text into employee name and box contents
					var array = http.responseText.split("__");
					$('new_shift').innerHTML = array[0];
					if(array[1]){
						$('notify').innerHTML = '<strong>' + array[1] + '</strong> has been notified of this request and must accept it before a manager can approve it.';
					}
					$('notify').style.display = 'block';
				}else{
					$('new_shift').innerHTML = '<h3 align="center">Choose a shift<br />below</h3><p>An error occured</p>';
				}
			break;
			case 1:
				$('new_shift').innerHTML = '<h3 align="center">Requesting&hellip;</h3><p></p>';
			break;
		}
	}
	http.send(params);
}

function notify(msg){
	// update notify box - Must include inner div for SlideUp effect
	$('notify').innerHTML = '<div>'+msg+'</div>';
	$('notify').style.display = 'block';
	
	setTimeout("Effect.SlideUp('notify', { duration: 0.8, scaleFrom: 53 });",2000);
}
function redirect(url){
	window.location = url;
}
function openWin(url,width,height){
	var newWindow = window.open(url, 'newWin', 'width='+width+',height='+height+',scrollbars=yes,resizable=yes,status=no,menubar=no,toolbar=no,location=no');
	if(window.focus) newWindow.focus();
}
function changeImage(newImage){
	// image comparison
	var newImageSplit = newImage.split("/");
	var newImageEnd = newImageSplit[newImageSplit.length-1];
	var oldSrc = $('screenshot').src;
	var oldSrcSplit = oldSrc.split("/");
	var oldSrcEnd = oldSrcSplit[oldSrcSplit.length-1];
	
	if(newImageEnd != oldSrcEnd){
		// drop out current image
		new Effect.DropOut($('screenshot'));
		// fade in new image
		var srcTimer = window.setTimeout('changeImageSource("'+newImage+'")',1000);
		var appearTimer = window.setTimeout('Effect.Appear(\'screenshot\', {duration:.3})',1500);
	}
}
function changeImageSource(imgSrc){
	$('screenshot').src = imgSrc;
	$('loader').style.backgroundImage = 'none';
}
function getElementHeight(Elem) {
	if (document.layers) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.height;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		xPos = elem.offsetHeight;
		return xPos;
	} 
}

function getElementWidth(Elem) {
	if (document.layers) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.width;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		xPos = elem.offsetWidth;
		return xPos;
	}
}

// callback functions
function clearObject(obj){
	obj.element.style.display = 'none';
	obj.element.innerHTML = '';
}

function setMaxLength() {
	var x = document.getElementsByTagName('textarea');
	var counter = document.createElement('div');
	counter.className = 'counter';
	for (var i=0;i<x.length;i++) {
		if (x[i].getAttribute('maxlength')) {
			var counterClone = counter.cloneNode(true);
			counterClone.relatedElement = x[i];
			counterClone.innerHTML = '<span>0</span>/'+x[i].getAttribute('maxlength')+' characters';
			x[i].parentNode.insertBefore(counterClone,x[i].nextSibling);
			x[i].relatedElement = counterClone.getElementsByTagName('span')[0];

			x[i].onkeyup = x[i].onchange = checkMaxLength;
			x[i].onkeyup();
		}
	}
}

function checkMaxLength() {
	var maxLength = this.getAttribute('maxlength');
	var currentLength = this.value.length;
	if (currentLength > maxLength)
		this.relatedElement.className = 'toomuch';
	else
		this.relatedElement.className = '';
	this.relatedElement.firstChild.nodeValue = currentLength;
	// not innerHTML
}
function ALstart() {	
	// Supprime les caractères invalides de la saisie
	if($('headerbgfield') && $('footerbgfield')){
		$('headerbgfield').onkeyup=function(e) {
			var rech=new RegExp(/[^0-9A-Fa-f]/g);
			this.value=this.value.replace(rech,'');
		}
	
		$('footerbgfield').onkeyup=function(e) {
			var rech=new RegExp(/[^0-9A-Fa-f]/g);
			this.value=this.value.replace(rech,'');
		}
		// Génération du color-picker
		ALmakeColorPicker();
	}
}

function ALmakeColorPicker() {
	myAddEventListener($('headerbgfield'),'focus',function() {
		$('color-picker').style.display = 'block';
		$('color-picker1').style.display = 'block';
		$('color-picker2').style.display = 'none';
	});
	
	myAddEventListener($('footerbgfield'),'focus',function() {
		$('color-picker').style.display = 'block';
		$('color-picker1').style.display = 'none';
		$('color-picker2').style.display = 'block';
	});
}
if(window.addEventListener) window.addEventListener('load',ALstart,false);



/* Date Selector callback functions */
function createSpanElement(argObj) {
        // Make sure the span doesn't exist already
        if(document.getElementById("EnglishDate_" + argObj.id)) return;

        // create the span node dynamically...
        var spn = document.createElement('span');
		spn.style.display = 'none';
            p   = document.getElementById(argObj.id).parentNode;
            
        spn.id = "EnglishDate_" + argObj.id;
        //p.parentNode.appendChild(spn);
		p.parentNode.insertBefore(spn,p.parentNode.firstChild);
        
        // Remove the bottom margin on the input's wrapper paragraph
        p.style.marginBottom = "0";
        
        // Add a whitespace character to the span
        spn.appendChild(document.createTextNode(String.fromCharCode(160)));
};

function showEnglishDate(argObj) {
        // Grab the span & get a more English-ised version of the selected date
        var spn = document.getElementById("EnglishDate_" + argObj.id),
            formattedDate = datePickerController.printFormattedDate(argObj.date, "l-cc-sp-F-sp-j-S-sp-Y", false);
        
        // Make sure the span exists before attempting to use it!
        if(!spn) {
                createSpanElement(argObj); 
                spn = document.getElementById("EnglishDate_" + argObj.id);
        };
        
        // Note: The 3rd argument to printFormattedDate is a Boolean value that 
        // instructs the script to use the imported locale (true) or not (false)
        // when creating the dates. In this case, I'm not using the imported locale
        // as I've used the "S" format mask, which returns the English ordinal
        // suffix for a date e.g. "st", "nd", "rd" or "th" and using an
        // imported locale would look strange if an English suffix was included
        
        // Remove the current contents of the span
        while(spn.firstChild) spn.removeChild(spn.firstChild);
        
        // Add a new text node containing our formatted date
        spn.appendChild(document.createTextNode(formattedDate));
		spn.style.display = 'block';
};

function displayTimeFields() {
        var p = document.getElementById("time-fields");
		if(p.style.display != 'block'){
			p.style.display = 'block';
		}
};

