var http = createRequestObject();
function createRequestObject() {
	var xmlhttp;
	// code for Mozilla, etc.
	if (window.XMLHttpRequest) {
		xmlhttp=new XMLHttpRequest()
	}
	// code for IE
	else if (window.ActiveXObject) {
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
	}
	else{
		alert("error: xmlhttp not supported");
	}
	return xmlhttp;
}
function changeStatus(id,status) {
    document.getElementById('msgID').className='msgActive';
    document.getElementById('msgID').innerHTML='Changing status...';
    http.open('get', 'rpcChangeStatus.php?ID='+id+'&changeStatus='+status,true);
    http.onreadystatechange = changeStatusResponse;
    http.send('');
}

function changeStatusResponse() {
//alert('CSR:'+http.readyState);
    if(http.readyState == 4){
        var response = http.responseText;
        if (response) {
            document.getElementById('msgID').innerHTML='Status Changed.';
        } else {
            document.getElementById('msgID').innerHTML='Failed to change status.';
        }
	    document.getElementById('msgID').className='msg';
    }
}

function addItem(itemID,itemType) {
    document.getElementById('msgID').className='msgActive';
    document.getElementById('msgID').innerHTML='Linking Item...';
    http.open('get', 'rpcAddItem.php?itemID='+itemID+"&itemType="+itemType);
    http.onreadystatechange = addItemResponse;
    http.send(null);
}

function addItemResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        if (response) {
            document.getElementById('msgID').innerHTML='Item linked.';
        } else {
            document.getElementById('msgID').innerHTML='Failed to link item.';
        }
	    document.getElementById('msgID').className='msg';
    }
	
}

function removeItem(itemID,itemType) {
    document.getElementById('msgID').className='msgActive';
    document.getElementById('msgID').innerHTML='Unlinking Item...';
    http.open('get', 'rpcRemoveItem.php?itemID='+itemID+"&itemType="+itemType);
    http.onreadystatechange = removeItemResponse;
    http.send(null);
}

function removeItemResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        if (response) {
            document.getElementById('msgID').innerHTML='Item unlinked.';
        } else {
            document.getElementById('msgID').innerHTML='Failed to link item.';
        }
	    document.getElementById('msgID').className='msg';
    }

}

function hideObj(id)
{
    if (document.getElementById(id)) {
        document.getElementById(id).style.display='none';
    }
    return true;
}

function showObj(id)
{
    if (document.getElementById(id)) {
        document.getElementById(id).style.display='block';
    }
    return true;
}

function showContentElem()
{
	elem = document.getElementById('mimeTypeID');
	type = elem.options[elem.selectedIndex].value;
	
	if (type == 'html') {
		showObj('htmlID');
		hideObj('uploadID');
	} else {
		hideObj('htmlID');
		showObj('uploadID');
	}
}

function clickclear(thisfield, defaulttext) {
	if (thisfield.value == defaulttext) {
		thisfield.value = "";
	}
}

function clickrecall(thisfield, defaulttext) {
	if (thisfield.value == "") {
		thisfield.value = defaulttext;
	}
}



function popUp(id){
	myPopup=window.open("/assets/resources/popup.html?id="+id+"","Resources","toolbar=no,scrollbars=yes,directories=no,status=no,menubar=no,resizable=yes,width=800,height=600");
	myPopup.opener.name = "mainWindow";
	return true;
}

function popEdit(location,width, height){
	var mypopEdit=window.open(location,"popEdit","toolbar=no,scrollbars=yes,directories=no,status=no,menubar=no,resizable=yes,width="+width+",height="+height);
	mypopEdit.focus();
	mypopEdit.opener.name = "mainWindow";
	return true;
}
function popResource(location,dimension){
	var splitArrayDimensions = dimension.split("x");
	var width=splitArrayDimensions[0];
	var height=splitArrayDimensions[1];
	var mypopResource=window.open(location,"popResource","toolbar=no,scrollbars=yes,directories=no,status=no,menubar=no,resizable=yes,width="+width+",height="+height);
	mypopResource.focus();
	mypopResource.opener.name = "mainWindow";
	return true;
}

function getLabelForId(id) {
    var label, labels = document.getElementsByTagName('label');
    for (var i = 0; (label = labels[i]); i++) {
        if (label.htmlFor == id) {
            return label;
        }
    }
    return false;
}
function checkEmail(emailID) {
    var email = document.getElementById(emailID);
    var label = getLabelForId(emailID);
    //if (email.value.indexOf('@') == -1 || email == '') { // Naive check for non empty string with @ sign
    if ((email.value.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1) || email == '') { // Naive check for non empty string with @ sign
        label.className = 'problem';
        return false;
	} else {
        label.className = 'completed';
        return true;
    }

}

function checkURL(urlID) {
    var url = document.getElementById(urlID);
    var label = getLabelForId(urlID);
    if ((url.value.search(/^[A-Za-z0-9]+$/) == -1) || url == '') { // Naive check for non empty string with @ sign
        label.className = 'problem';
        return false;
	} else {
        label.className = 'completed';
        return true;
    }

}




function checkTime(timeID) {
	// Checks if time is in HH:MM:SS AM/PM format.
	// The seconds and AM/PM are optional.
    
    var timeSTR = document.getElementById(timeID);
    var label = getLabelForId(timeID);
	
	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
	
	var matchArray = timeSTR.value.match(timePat);
	if (matchArray == null) {
	//alert("Time is not in a valid format or is empty.");
	label.className = 'problem';
	return false;
	}
	hour = matchArray[1];
	minute = matchArray[2];
	second = matchArray[4];
	ampm = matchArray[6];
	
	if (second=="") { second = null; }
	if (ampm=="") { ampm = null }
	
	if (hour < 0  || hour > 23) {
	//alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
	label.className = 'problem';
	return false;
	}
	if (hour <= 12 && ampm == null) {
	if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
	//alert("You must specify AM or PM.");
	label.className = 'problem';
	return false;
	   }
	}
	if  (hour > 12 && ampm != null) {
	//alert("You can't specify AM or PM for military time.");
	label.className = 'problem';
	return false;
	}
	if (minute<0 || minute > 59) {
	//alert ("Minute must be between 0 and 59.");
	label.className = 'problem';
	return false;
	}
	if (second != null && (second < 0 || second > 59)) {
	//alert ("Second must be between 0 and 59.");
	label.className = 'problem';
	return false;
	}
	label.className = 'completed';
	return true;
}





function resetLables(ID) {
    var label = getLabelForId(ID);
        label.className = 'required';

}

function resetEmptyLables(ID) {
    var label = getLabelForId(ID);
        label.className = '';

}



function checkPhone(phoneID) {
    var phone = document.getElementById(phoneID);
    var label = getLabelForId(phoneID);
    var digits = phone.value.replace(/[^0-9]/ig, '');
    if (phone.value == ''){
        label.className = '';
        return;
    }
    if (!digits) {
        label.className = 'problem';
        phone.value = '';
       return false;
    }
    if (digits.length == 10) {
        phone.value = '(' + digits.substring(0, 3) + ') ' + 
            digits.substring(3, 6) + '-' + 
            digits.substring(6, 10);
        label.className = 'completed';
		return true;
    } else {
        label.className = 'problem';
        phone.value = digits;
		return false;
    }
}

function checkPhoneRequired(phoneID) {
    var phone = document.getElementById(phoneID);
    var label = getLabelForId(phoneID);
    var digits = phone.value.replace(/[^0-9]/ig, '');
    if (phone.value == ''){
        label.className = 'problem';
        return false;
    }
    if (!digits) {
        label.className = 'problem';
        phone.value = '';
        return false;
    }
    if (digits.length == 10) {
        phone.value = '(' + digits.substring(0, 3) + ') ' + 
            digits.substring(3, 6) + '-' + 
            digits.substring(6, 10);
        label.className = 'completed';
		return true;
    } else {
        label.className = 'problem';
		phone.value = digits;
		return false;
    }
}
function checkRequired(id) {
    var formfield = document.getElementById(id);
    var label = getLabelForId(id);
    if (formfield.value.length == 0) {
        label.className = 'problem';
		return false;
    } else {
        label.className = 'completed';
		return true;
    }
}

function checkRequiredPullDown(id) {
    var formfield = document.getElementById(id);
    var label = getLabelForId(id);
    if (!(formfield.selectedIndex >= 0) || (formfield.selectedIndex=='')) {
        label.className = 'problem';
		return false;
    } else {
        label.className = 'completed';
		return true;
    }
}

function checkFile(photoid,captionid) {
    var photo = document.getElementById(photoid);
    var labelCaption = getLabelForId(captionid);
    var caption = document.getElementById(captionid);
    
    if (photo.value != '' && caption.value.length == 0) {
        labelCaption.className = 'problem';
		return false;
    } else {
        labelCaption.className = 'completed';
		return true;
    }
}

function checkCheckBox(id) {
    var formfield = document.getElementById(id);
    var label = getLabelForId(id);
	var l = formfield.length;
	for (i=0; i<l; i++)
	if (formfield[i].checked) {
			label.className = 'completed';
			return true;
		} else {
			label.className = 'problem';
			return false;
		}


    if (formfield.value.length == 0) {
        label.className = 'problem';
			return false;
    } else {
        label.className = 'completed';
			return true;
    }
}


function changeGallery(drag, drop, section) {
	//var image = element.id;
	var splitArraydrag = drag.id.split("_");
	var splitArraydrop = drop.id.split("_");
	var resourceID = splitArraydrag[1];
	var galleryID = splitArraydrop[1];
	//$('ajaxResponse').innerHTML =  '<img src="/assets/images/ajaxAnimation.gif" width="399" height="4">';
	document.body.style.cursor = 'wait';
	
	
	http.open('get', '/rpcChangeGallery.php?resourceID='+resourceID+'&galleryID='+galleryID+'&galleryType='+section,true);
    http.onreadystatechange = function(){
		if(http.readyState == 4){
        	var response = http.responseText;
			if (response) {
					$('galleryMSG').innerHTML='';
					$('ajaxResponse').innerHTML =  'Resource: ' + drag.title + ' moved to the ' + drop.title + ' gallery.';
					document.body.style.cursor = 'default';
			} else {
				//document.getElementById('protegeSelfRank').innerHTML='Failed to update status.';
					document.body.style.cursor = 'default';
			}
    	}
    }
    http.send(null);
}

function changeOrder() {
	var str =Sortable.serialize('imagesContainer');
	var url = "/rpcChangeOrder.php";
	document.body.style.cursor = 'wait';

	http.open('POST', url, true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
    http.onreadystatechange = function(){
		if(http.readyState == 4){
			document.body.style.cursor = 'default';
    	}
    }
    http.send(str);
}// End changeOrder function

function confirmDelete(delUrl,message) {
  if (confirm(message)) {
	document.location = delUrl;
  }
}

function changePerms(id) {
	document.body.style.cursor = 'wait';
    http.open('get', '/rpcEditGalleryPerms.php?ID='+id,true);
    http.onreadystatechange = function(){
		if(http.readyState == 4){
        	var response = http.responseText;
			var graphicID = $('lock_'+id).parentNode.id;
			if (response=='Lock') {
				//$(graphicID).style.backgroundImage = 'url(/assets/images/icons/unlocked.gif)';
				$('lock_'+id).src =  '/assets/images/icons/unlocked.gif';
				document.body.style.cursor = 'default';
			}
			else if (response=='Unlock') {
				//$('lock_'+id).innerHTML =  response;
				//$(graphicID).style.backgroundImage = 'url(/assets/images/icons/locked.gif)';
				$('lock_'+id).src =  '/assets/images/icons/locked.gif';
				document.body.style.cursor = 'default';
			}
			
			else {
				$('ajaxResponse').innerHTML = 'Failed to update status.';
				document.body.style.cursor = 'default';
			}
    	}
    }
    http.send(null);
}

function changeOptions(id) {
	document.body.style.cursor = 'wait';
    http.open('get', '/rpcEditGalleryOptions.php?ID='+id,true);
    http.onreadystatechange = function(){
		if(http.readyState == 4){
        	var response = http.responseText;
			if (response=='Download') {
				$('options_'+id).src =  '/assets/images/icons/open.gif';
				$('link_'+id).target =  '_blank';
				$('link_'+id).href =  '/resources/?resourceID='+id;
				document.body.style.cursor = 'default';
			}
			else if (response=='Open') {
				$('link_'+id).target =  '_self';
				$('link_'+id).href =  '/resources/?resourceID='+id;
				$('options_'+id).src =  '/assets/images/icons/download.gif';
				document.body.style.cursor = 'default';
			}
			
			else {
				$('ajaxResponse').innerHTML = 'Failed to update status.';
				document.body.style.cursor = 'default';
			}
    	}
    }
    http.send(null);
}
