var pubTabs = undefined;
var accordian = undefined;
var pubid = undefined;
var pubHelpShown = false;

function scrollToTop() { $('html, body').animate({scrollTop:0}, 'normal'); }

function scrollTo(selector) { $('html,body').animate({scrollTop: $(selector).offset().top}, 'normal'); }
function showModal(pvar) { 
	$('' + pvar + '').overlay().load();
}
function showCheck(pvar){
	$('' + pvar + '').overlay().load();
}
function hideModal(pvar) { 
	$('' + pvar + '').overlay().close(); 
}
function resetURL() { window.location.href=window.location.href.replace('?l=true','').replace('&l=true',''); }

function home() { 
	closeConfirmation();
	window.location.href = "/index.html";
}
function setPubId(pvar) { 
	pubid = pvar;
}
function publish_embed() { 
	closeConfirmation();	
	window.location.href = "/embed/publish.html";
}

function publish() {
	closeConfirmation();	
	window.location.href = "/publish.html";
}
function publish_embed_home() { 
	closeConfirmation();
	window.location.href = "/embed/publish-main.html";
}

function publish_home()  {
	closeConfirmation();
	window.location.href = "/publish-main.html";
}

function voucherPurchase() { 
	closeConfirmation();
	showWait(true);
	$('#transport').attr("src","/voucher-purchase/" + pubid);
}

function disableButtons(pvar) { 
	if (pvar) { 
		if ($('.buttons').length != 0 && $('.processing').length != 0) { 
			$('.buttons').hide();
			$('.processing').show();
		}
	}else { 
		if ($('.buttons').length != 0 && $('.processing').length != 0) {
			$('.buttons').show();
			$('.processing').hide();
		}
	}
}
function showWait(pvar) { 
	if (pvar) { 
		$('body').css('cursor','wait');
	}else {
		$('body').css('cursor','default');
	}
}
function showPreview() { 
	if (pubid != undefined) { 
		window.location.href = "/IPCOM/" + pubid.replace("IPCOM","").replace("D","");
	}
	
}
function togglePublishHelp() { 
	if (pubHelpShown) { 
		$('.publish-help').each(function() { $(this).hide();});
		pubHelpShown = false;
	}else { 
		$('.publish-help').each(function() { $(this).show();});
		pubHelpShown = true;
	}
}
function showDownload() { 
	closeConfirmation();
	showModal('#doc-download');
}
function closeConfirmation() { 
	hideModal("#confirmation-dialog");
}
function showConfirmation(text, buttons, buttonText,type,methods) { 
	try {
		$("#confirmation-text").empty();
		$("#confirmation-text").append(text);
		$("#confirmation-text").removeClass('warning').removeClass('error').addClass(type);
		$("#confirm-buttons").empty();
		if (buttons == 2) { 
			$("#confirm-buttons").css("padding-left","125px");
			$("#confirm-buttons").append(
						"<div class='buttons' id='button1'>" + 
							"<button type='button'><img src='/images/icons/accept.png'/>" + buttonText[0] + "</button>" + 
						"</div>");
			$("#confirm-buttons").append(
					"<div class='buttons' id='button2'>" + 
						"<button type='button'><img src='/images/icons/cancel.png'/>" + buttonText[1] + "</button>" + 
					"</div><div class='clear'></div>");
			$("#button1").bind('click',methods[0]);
			$("#button2").bind('click',methods[1]);
		}else { 
			$("#confirm-buttons").css("padding-left","165px");
			$("#confirm-buttons").append(
					"<div class='buttons' id='button1'>" + 
						"<button type='button'><img src='/images/icons/accept.png'/>" + buttonText[0] + "</button>" + 
					"</div><div class='clear'></div>");
			$("#button1").bind('click',methods[0]);
		}	
		//if (maskoverlay != undefined) { maskoverlay.load();}
		$("#confirmation-dialog").overlay().load();
	}catch(e) { alert(e); } 
}
function autoSelectFileType() { 
	
	var filename = $('#primaryFile').val();
	if (filename != undefined && filename != '') { 
		filename = filename.toLowerCase();
		if (filename.indexOf("doc") > -1 && filename.indexOf("docx") == -1){
			$('#primaryFileType').val('Microsoft Word Document');
		}else if (filename.indexOf("docx") > -1){
			$('#primaryFileType').val('Microsoft Word 2007 Document');
		}else if (filename.indexOf("html") > -1) { 
			$('#primaryFileType').val('HTML');
		}else if (filename.indexOf("ppt") > -1 && filename.indexOf("pptx") == -1){
			$('#primaryFileType').val('PPT');
		}else if (filename.indexOf("pptx") > -1){
			$('#primaryFileType').val('PPTX');
		}else if (filename.indexOf("rtf") > -1){
			$('#primaryFileType').val('RTF');
		}else if (filename.indexOf("pdf") > -1) { 
			$('#primaryFileType').val('PDF');
		}else if (filename.indexOf("txt") > -1){
			$('#primaryFileType').val('Plain Text');
		}else { 
			$('#primaryFileType').val('No format specified');
		}
	}
}

function toggleNewFiles() {
	$(".primary").replaceWith("<input type='file' name='primaryFile' id='primaryFile'/><br/>");
	$(".primary-desc").replaceWith(
						"<select name='primaryFileType' id='primaryFileType'> " + 
							"<option value='No format specified'>Select file type: </option>" + 
							"<option value='No format specified'>----------------- </option>" + 
							"<option value='Microsoft Word Document'>*.DOC - Microsoft Word Document </option>" + 
							"<option value='Microsoft Word 2007 Document'>*.DOCX - Microsoft Word 2007 Document </option>" + 
							"<option value='HTML'>*.HTM - HTML Document </option>" + 
							"<option value='PPT'>*.PPT - Microsoft PowerPoint Document</option>" + 
							"<option value='PPTX'>*.PPTX - Microsoft PowerPoint 2007 Document</option>" + 
							"<option value='RTF'>*.RTF - Rich Text Format Document</option>" + 
							"<option value='PDF'>*.PDF - Adobe PDF Document</option>" + 
	    				"</select>" 
			);
	$(".attachment").replaceWith("<input type='file' name='attachmentFile'/><br/>");
	$(".attachment-desc").replaceWith(
						"<select name='attachmentFileType'>" +
							"<option value='No format specified'>Select file type: </option>" +
							"<option value='No format specified'>----------------- </option>" +
							"<option value='Zip Archive'>*.ZIP - Zipped Archive </option>" +
							"<option value='Unix Archive'>*.TAR/*.TZ - UNIX Archive </option>" +
							"<option value='Windows Bitmap'>*.BMP - Windows Bitmap </option>" +
							"<option value='GIF Image'>*.GIF - GIF Image </option>" +
							"<option value='JPEG Image'>*.JPG/*.JPEG - JPEG Image </option>" +
							"<option value='PNG Image'>*.PNG - PNG Image </option>" +
							"<option value='TIFF Image'>*.TIF/*.TIFF - TIFF Image </option>" +
							"<option value='Other/Unknown'>Other/Unknown</option>" +
						"</select><br/>"
			);
	
	$(".review").attr('href','/publish-review.html');
	$("#upload").attr("enctype","multipart/form-data");
	$("#useExistingFiles").val("false");
}

function enableNextStep() {
	$(".second").replaceWith('<li><a href="#step-2">' + publishWizardText.biblio + '</a></li>');
	pubTabs = $("ul.tabs-nav").tabs("div.tabs > div.tabs-panel");
}

function enableRemainingTabs() {
	$(".third").replaceWith('<li><a href="#step-3">' + publishWizardText.docProcessing + '</a></li>');
	$(".fourth").replaceWith('<li><a href="#step-4">' + publishWizardText.relatedPeople + '</a></li>');
	$(".fifth").replaceWith('<li><a href="#step-5">' + publishWizardText.relatedDocs + '</a></li>');
	$(".sixth").replaceWith('<li><a href="/publish-review.html">' + publishWizardText.review + '</a></li>');
	$(".seventh").replaceWith('<li><a href="#step-7">' + publishWizardText.upload + '</a></li>');
	pubTabs = $("ul.tabs-nav").tabs("div.tabs > div.tabs-panel",{
					onBeforeClick : function(event,index) {
						if (index == 5) {
							$("#transport").attr("src",this.getTabs().eq(index).attr("href"));
						}
					}
				});
}

function nextTab(index) {
	showWait(false);
	if (pubTabs != undefined) { 
		pubTabs.data("tabs").click((index - 1));
	}else { 
		alert("Tabs for some reason is not enabled.");
	}
}
function prevTab(index) {
	if (pubTabs != undefined) { 
		pubTabs.data("tabs").click((index - 1));
	}else { 
		alert("Tabs for some reason is not enabled.");
	}
}
var counterName = undefined;

function removeElement(pvar) {

	if (pvar != undefined) {
		var id = pvar.parentNode.getAttribute("id");
		
		if (id != undefined) {
			var element_count = parseInt(id.substring( (id.lastIndexOf("-") + 1)) );
			var counter = document.getElementById(counterName);
			
			if (counter != undefined) {
				counter = parseInt(counter.value);
				if (element_count < counter){
					alert(messageText.removeElement);
				}else if (element_count == counter){
					pvar.parentNode.parentNode.removeChild(pvar.parentNode);
					counter--;
					document.getElementById(counterName).value = counter;
				}
			}
		}
	}else { alert("Error removing elements"); }
}
function copyElement(src, dest,before,index){
	var copy = "";
	var count = document.getElementById(index);
	
	if (count != undefined) {
		count = parseInt(count.value);
		count++;
		counterName = index;
		if (document.getElementById(src) != undefined) {
			copy = document.getElementById(src).cloneNode(true); 
			copy.id = (copy.id.substring(0,copy.id.lastIndexOf("-")) + "-" + count);
			var fields = copy.childNodes;
			for (var i = 0; i < fields.length;i++){
				var name = fields[i].name;

				if (name != undefined) {  
					fields[i].name = (name.substring(0,name.lastIndexOf("-")) + "-" + count);
					fields[i].id = (name.substring(0,name.lastIndexOf("-")) + "-" + count);
				}
			}
			if (document.getElementById(dest) != undefined) {
				document.getElementById(dest).parentNode.insertBefore(copy, document.getElementById(dest));
			}

			
			var link = document.createElement("a");
			
			var insert = document.getElementById((before + count));
			if (insert != undefined) {
				copy.insertBefore(link, insert);
			}else {
				copy.appendChild(link);
			}

			if (document.all) { 
				link.style.styleFloat = "right";
			}else {
				link.style.cssFloat = "right";
			}
			link.href = "#";
			link.innerHTML = buttonText.remove;
			link.onclick = function() { removeElement(this);return false;};
			document.getElementById(index).value = count;
			
		}
	}else { alert("Error during addition of elements"); }
	

}

function validate(pvar/*form*/,list /*check list*/){
	var canSubmit = true;
	showWait(true);
	if (list != undefined || list != null) { 
		$(pvar).find(":input").each(function() { 
			if ($.inArray(this.name,list) > -1){
				// required field
				if (this.type == 'checkbox'){
					if (!$(this).is(':checked')){
						canSubmit = false;
					}
				}else {
					if ($(this).val() == '') {
						$(this).toggleClass('error');
						canSubmit = false;
					}
				}
			}
		});
	}
	if (!canSubmit) { showWait(false);alert(messageText.formValidation); }
	return canSubmit;
}

function formatDateString(d,sep) { 
	var retval = "";
	if (d != null && d != undefined) { 
		retval = d.getFullYear(); // already YYYY
		retval += sep;
		retval += ((d.getMonth() + 1) < 10)?('0' + (d.getMonth() + 1)):(d.getMonth() + 1);
		retval += sep;
		retval += (d.getDate() < 10)?('0' + d.getDate()):d.getDate();
	}
	return retval;
}
function ensureProperDate(element) { 
	var retVal = true;
	try { 
		for (var i = 0; i < element.length;i++) {
			var name = 'input[name="' + element[i] + '"]';
			if ($(name).val() == '') { continue; }
			var d = new Date($(name).val());
			if (!isNaN(d.getFullYear()) && !isNaN(d.getMonth()) && !isNaN(d.getDate())){
				$(name).val(formatDateString(d,'/'));
			}else { disableButtons(false);alert("Invalid format in date field");$(name).toggleClass('error');retVal = false;}
		}
	}catch(e) {
		alert(e);
		retVal = false;
	}
	return retVal;
}

function validateform(pvar,dialog, list) {
	
	if (validate(pvar,list)){
		if (dialog != undefined && dialog.length > 0){
			hideModal(dialog);
		}
		return true;
	}
	disableButtons(false);
	return false;
}

function checkNewPassword(){
	var nw_pw = document.getElementById("newpw");
	var confirm = document.getElementById("confirm");
	if (nw_pw != undefined && confirm != undefined){
		if (nw_pw.value == confirm.value){
			return true;
		}else { 
			alert("Passwords do not match.");		
		}
	}
	return false;
}


function addToFavorites() {
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(document.title, top.location.href,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite(top.location.href, document.title); 
	}	
}


