//adding messages vars.
var validateAcceptDecline = "Please select either Accept or Decline for each row.";
var publicCatalogValidation  = "Before a title can be added to the public catalog it needs the publisher, author and publication date fields completed, one reading option selected, as well as a cover image. Please make the required updates and try again.";
var reviewOrganizationValidation = "Please select review organization";
var mandatoryChkMessage = "Please complete the following required fields";
var recordDeleteConfirmationMessage = "Do you want to delete the record?";
var titleDeleteConfirmationMessage = "Do you want to delete the Title?";
var titleActiveReviewMessage = "If you'd like to save review and report data for this title, click Cancel. Then archive the title instead. Otherwise, click OK to delete the title."
var titleActiveReviewMessage_Old = "At least one review request has been sent out for this Title. By clicking 'Ok', you will no longer receive review updates and all information associated with this Title be removed. Also, recipients of the Title will no longer have access to it.";
function validateTab()
{
		var flgSubmission=true;
		var flgpubDate=true;
		var flgInitial=true;
		var flgDistributor=true;
		var flgRequest_type=false;
		var flgPrintRunSp = true;
		var flgDistributorSp = true;
		var flgpubDateValid = true;
        /*********/
        var Obj = document.sendReviewReq.radFRO;
        for (var i=0; i < Obj.length; i++)
        {
            if (Obj[i].checked)
            {
               flgRequest_type=true;
            }
        }
        /*********/
		if( document.getElementById('lstSubmission').options[document.getElementById('lstSubmission').selectedIndex].text=="Select"){
				 flgSubmission=false;
			}
		if (document.getElementById('txtDistributor').value == ""){
				 document.getElementById('txtDistributor').focus();
				 flgDistributor=false;
		}
		 if(!isAlphNum(document.getElementById('txtDistributor').value)) {
				document.getElementById('txtDistributor').focus();
				flgDistributorSp=false;
		 }
		 
		 if (document.getElementById('txtInitial_print_run').value == "" ){
				 document.getElementById('txtInitial_print_run').focus();
				 flgInitial=false;
			}
		 if(!onlyNum(document.getElementById('txtInitial_print_run').value)) {
				 document.getElementById('txtInitial_print_run').focus();
				 flgPrintRunSp=false;
		 }
		 if (document.getElementById('pub_Date').value == ""){
				 document.getElementById('pub_Date').focus();
				 flgpubDate=false;
		}
		if (document.getElementById('pub_Date').value != "" && isDate(document.getElementById('pub_Date').value)==false){
				 document.getElementById('pub_Date').focus();
				 flgpubDateValid=false;
		}
		var msgAlert="";
		if(!flgRequest_type){
		 msgAlert="Review Organization\n";
		 }
		if(!flgSubmission){
		 msgAlert="missing Submission Category\n";
		 }
		if(!flgpubDate){
		 msgAlert=msgAlert+"missing Publication Date\n";
		 }
		 if(!flgpubDateValid){
		 msgAlert=msgAlert+"Please enter valid publication date in MM/DD/YYYY format\n";
		 }
		 if(!flgInitial){
		 msgAlert=msgAlert+"missing Initial Print Run\n";
		 }
		 if(!flgPrintRunSp) {
		  msgAlert=msgAlert+"Only numbers are allowed in Initial Print Run\n";
		 }
		 if(!flgDistributor){
		 msgAlert=msgAlert+"missing Distributors of this Title\n";
		 }
		 if(!flgDistributorSp) {
		  msgAlert=msgAlert+"No symbols and special characters are allowed in distributor name\n";
		 }
		 if(msgAlert!=""){
		 alert(mandatoryChkMessage+":\n"+msgAlert)
		 return false;
		 }
         else{
         return true;
         }
}
function nextTab()
	{
        /*********/
        var flagCount=0;//flag to check whether radio button checked or not
        var Obj = document.sendReviewReq.radFRO;
        for (var i=0; i < Obj.length; i++)
        {
            if (Obj[i].checked)
            {
               flagCount++;
            }
        }
        if(flagCount == '0')
		{
			alert(reviewOrganizationValidation);
			return false;
		}
        /**********/
    
		// JS validations added for mandatory fields checking.
		 if(document.getElementById("tabIndex").value == 1)
	   {
	    	var flgSubmission=true;
            /*********/
           Obj = document.sendReviewReq.radFRO;
            for (i=0; i < Obj.length; i++)
            {
                if (Obj[i].checked)
                {
                  flgRequest_type=true;
                }
                else{
                  flgRequest_type=false;
                }
            }
        /*********/
	   }
	   if(document.getElementById("tabIndex").value == 1)
	   {
			if(validateTab() == false)
			return false;
	   }

	 if(document.getElementById("tabIndex").value != 2)
	 {
		var tInd = eval(document.getElementById("tabIndex").value)+1;
		showTab('dhtmlgoodies_tabView1',tInd);
		document.getElementById("tabIndex").value = tInd;
		//document.getElementById("previousBtn").disabled = false;
		document.getElementById("disabledPreviousBtn").style.display = 'none';
		document.getElementById("previousBtn").style.display = 'block';
	 }
	 if(document.getElementById("tabIndex").value == 2)
	 {
		Element.show('finishBtn');
		Element.hide('nextBtn');
	 }
		 return true;
 }
function showConformation()
	{
        /*********/
        var flagCount=0;//flag to check whether radio button checked or not
        var Obj = document.sendReviewReq.radFRO;
        for (var i=0; i < Obj.length; i++)
        {
            if (Obj[i].checked)
            {
               flagCount++;
            }
        }
        if(flagCount == '0')
		{
			alert(reviewOrganizationValidation);
			return false;
		}
        /**********/
		if(!isValidTrackingNo(document.getElementById('txtTracking_number').value))
		{
			alert('Please enter valid tracking number')
			document.getElementById('txtTracking_number').focus();
			return false;
		}
		var lstSubmission=document.getElementById('lstSubmission').options[document.getElementById('lstSubmission').selectedIndex].text;
		var lstShippingService = document.getElementById('lstShippingService').options[document.getElementById('lstShippingService').selectedIndex].text;
		var trackingNumber = document.getElementById('txtTracking_number').value;
		var lstLeadTitle = document.getElementById('lstLeadTitle').value;
		var lstReprint = document.getElementById('lstReprint').value;
		var lstImport = document.getElementById('lstImport').value;
		if(lstLeadTitle=='0')
			{
			   document.getElementById('cnfLeadTitle').innerHTML ="No";
			}
		else{
				document.getElementById('cnfLeadTitle').innerHTML ="Yes";
		    }
		if(lstReprint=='0')
			{
			   document.getElementById('cnfReprint').innerHTML ="No";
			}
		else{
				document.getElementById('cnfReprint').innerHTML ="Yes";
		    }
		if(lstImport=='0')
			{
			   document.getElementById('cnfImport').innerHTML ="No";
			}
		else{
				document.getElementById('cnfImport').innerHTML ="Yes";
		    }

		 document.getElementById('cnfPublicationDate').innerHTML = document.getElementById('pub_Date').value;
		 document.getElementById('cnfInitialPrintRun').innerHTML = document.getElementById('txtInitial_print_run').value;
		 document.getElementById('cnfDistributor').innerHTML = document.getElementById('txtDistributor').value;
		 document.getElementById('cnfPhysicalGalleyAddress').innerHTML = document.getElementById('txtAddress').value;
		 document.getElementById('txtSubmissionNote').innerHTML = document.getElementById('txtSubmissionNotes').value;
		 document.getElementById('cnfSubmissionCategory').innerHTML = lstSubmission;
		 if(lstShippingService != "Select One" && trackingNumber != "")
		 {
		 	document.getElementById('cnfShippingTrackingNo').innerHTML = lstShippingService+"<br>"+trackingNumber;
		 }
		Element.hide('GenericBlock')
		Element.hide('organizationBlock')
		//Element.hide('lstRequest_type')
        Element.hide('froGuideline');
        Element.hide('froOptions');
		Element.show('ConformationPanel')
		Element.hide('MainBlock')
 }
function radCheck(obj)
{
	if(obj.value == 'org_request')
	{
		document.getElementById("btnText").innerHTML = "NEXT";
		Element.hide('GenericBlock')
        Element.hide('headerText')
        Element.show('headerTextFro')
		Element.show('organizationBlock')
        Element.show('froGuideline');
        Element.show('froOptions');
		Element.show('buttondiv')
	}
	else
	{
		document.getElementById("btnText").innerHTML = "SEND";
		Element.hide('organizationBlock')
        Element.show('headerText')
        Element.hide('headerTextFro')
		Element.show('GenericBlock')
        Element.hide('froGuideline');
        Element.hide('froOptions');
		Element.hide('buttondiv')
	}
}
function goToTab()
{
        Element.hide('GenericBlock')
		Element.show('organizationBlock')
        Element.hide('froGuideline');
        Element.hide('froOptions');
		Element.hide('ConformationPanel')
		Element.show('MainBlock')
}

function getGroupDetails()
{

	var id = $('group_name').value;
	var html = $(id).innerHTML;
	Element.update('Names',html);

}

function addContributor()
{
	var noOfContributors = $F('totalContributors');
	var lastrow = "contributor_row_"+$F('totalContributors');
	noOfContributors++;
	var row = "<tr id='contributor_row_"+noOfContributors+"'><td align='left' width='50%'><input type='text' name='contributor_"+noOfContributors+"' id='contributor_"+noOfContributors+"' style='font-size:11px;width:100%'></td>"+
				"<td align='left' width='50%'><select name='cont_role_"+noOfContributors+"' id='cont_role_"+noOfContributors+"' style='font-size:11px;width:100%'><option value='' selected>Select One</option>"+
									"<option  value='A02'>With</option>"+
									"<option  value='A03'>Screenplay by</option>"+
									"<option  value='A05'>Lyrics by</option>"+
									"<option  value='A06'>By (composer)</option>"+
									"<option  value='A07'>By (artist)</option>"+
									"<option  value='A08'>By (photographer)</option>"+
									"<option  value='A09'>Created by</option>"+
									"<option  value='A11'>Designed by</option>"+
									"<option  value='A12'>Illustrated by</option>"+
									"<option  value='A13'>Photographs by</option>"+
									"<option  value='A14'>Text by</option>"+
									"<option  value='A15'>Preface by</option>"+
									"<option  value='A16'>Prologue by</option>"+
									"<option  value='A17'>Summary by</option>"+
									"<option  value='A18'>Supplement by</option>"+
									"<option  value='A19'>Afterword by</option>"+
									"<option  value='A20'>Notes by</option>"+
									"<option  value='A21'>Commentaries by</option>"+
									"<option  value='A22'>Epilogue by</option>"+
									"<option  value='A23'>Foreword by</option>"+
									"<option  value='A24'>Introduction by</option>"+
									"<option  value='A25'>Footnotes by</option>"+
									"<option  value='A26'>Memoir by</option>"+
									"<option  value='A27'>Experiments by</option>"+
									"<option  value='A31'>Book and lyrics by</option>"+
									"<option  value='A32'>Contributions by</option>"+
									"<option  value='A33'>Appendix by</option>"+
									"<option  value='A34'>Index by</option>"+
									"<option  value='A35'>Drawings by</option>"+
									"<option  value='A36'>Cover design or artwork by</option>"+
									"<option  value='A38'>Original author</option>"+
									"<option  value='A39'>Maps by</option>"+
									"<option  value='A40'>Inked or colored by</option>"+
									"<option  value='B01'>Edited by</option>"+
									"<option  value='B02'>Revised by</option>"+
									"<option  value='B03'>Retold by</option>"+
									"<option  value='B06'>Translated by</option>"+
									"<option  value='B07'>As told by</option>"+
									"<option  value='B09'>Series edited by</option>"+
									"<option  value='B10'>Edited and translated by</option>"+
									"<option  value='B11'>Editor-in-chief</option>"+
									"<option  value='B12'>Guest editor</option>"+
									"<option  value='B13'>Volume editor</option>"+
									"<option  value='B14'>Editorial board member</option>"+
									"<option  value='B15'>Editorial coordination by</option>"+
									"<option  value='B16'>Managing editor</option>"+
									"<option  value='B17'>Founded by</option>"+
									"<option  value='B19'>Associate editor</option>"+
									"<option  value='B20'>Consultant editor</option>"+
									"<option  value='B21'>General editor</option>"+
									"<option  value='B22'>Dramatized by</option>"+
									"<option  value='B23'>General rapporteur</option>"+
									"<option  value='B99'>Other adaptation by</option>"+
									"<option  value='C01'>Compiled by</option>"+
									"<option  value='C02'>Selected by</option>"+
									"<option  value='C99'>Other compilation by</option>"+
									"<option  value='D01'>Producer</option>"+
									"<option  value='D02'>Director</option>"+
									"<option  value='D03'>Conductor</option>"+
									"<option  value='D99'>Other direction by</option>"+
									"<option  value='E07'>Read by</option>"+
									"<option  value='Z99'>Other</option>"+

								"</select>"+
							"</td>"+
							"</tr>";
	new Insertion.After(lastrow,row);
	$('totalContributors').value = noOfContributors;

}


function addUrl()
{
	var noOfUrls = $F('totalUrls');
	var lastrow = "url_row_"+$F('totalUrls');
	noOfUrls++;
	var row = "<tr id='url_row_"+noOfUrls+"'><td align='Center' width='150'><input type='text' name='desc_"+noOfUrls+"' id='desc_"+noOfUrls+"' style='font-size:11px;width:145;'></td>"+
				"<td align='Center' width='150'><input type='text' name='link_"+noOfUrls+"' id='link_"+noOfUrls+"' style='font-size:11px;width:145;'>"+
							"</td>"+
							"</tr>";
	new Insertion.After(lastrow,row);
	$('totalUrls').value = noOfUrls;

}


function DeletePrintEdition(id)
{
    answer = confirm(recordDeleteConfirmationMessage);

    if (answer !=0)
    {
    	var row = 'printEdition_row_'+id;
    	$('printEditionType_'+id).value ="";
    	$('printPages_'+id).value ="";
    	$('printPageSize_'+id).value ="";
    	$('printPrice_'+id).value ="";
    	$('printISBN_'+id).value ="";
    	$('printDate_'+id).value ="";
    	Element.hide(row);
    }
}

function DeleteAudioEdition(id)
{
    answer = confirm(recordDeleteConfirmationMessage);
	if (answer !=0)
    {
    	var row = 'audioEdition_row_'+id;
    	$('audioEditionType_'+id).value ="";
    	$('audioTitle_'+id).value ="";
    	$('audioNarrator_'+id).value ="";
    	$('audioLanguage_'+id).value ="";
    	$('audioRunTime_'+id).value ="";
    	$('audioPrice_'+id).value ="";
    	$('audioISBN_'+id).value ="";
    	$('audioDate_'+id).value ="";
    	Element.hide(row);
    }
}

function DeleteEBookEdition(id)
    {
    answer = confirm(recordDeleteConfirmationMessage);

    if (answer !=0)
    {
    	var row = 'eBookEdition_row_'+id;

    	$('eBookEditionType_'+id).value ="";
    	$('eBookSize_'+id).value ="";
    	$('eBookPrice_'+id).value ="";
    	$('eBookISBN_'+id).value ="";
    	$('eBookDate_'+id).value ="";
    	Element.hide(row);
    }
}

var GalleyRowDeleted;
function DeleteMediaRecord(id,galleyID,ele)
{
    answer = confirm("Do you want to remove the media file?");
	var lastRow = $('lastMediaRow').value;

	//Check if it's the last element
	// The previous row will become the last row
	if (ele == "media_"+lastRow)
	{
		var previousID = $(ele).previous().readAttribute('id');
		lastMediaID = previousID.substring(previousID.indexOf("_")+1,previousID.length);
		$('lastMediaRow').value = lastMediaID;
	}

	if (answer !=0)
    {
    	var url = "AJAXHandler.php";
    	var pars = "module=project&func=deleteMediaRecord&id="+id+"&galley="+galleyID;
    	GalleyRowDeleted = ele;
    	var myAjax = new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: pars,
				onComplete: HandleMediaDelete,
				onFailure: AJAXReportError
			});


    }
}

//Delete media row
function DeleteMediaRecordRow(ele)
{
    answer = confirm("Do you want to remove the media file?");
	var lastRow = $('lastMediaRow').value;

	//Check if it's the last element
	// The previous row will become the last row
	if (ele == "media_"+lastRow)
	{
		var previousID = $(ele).previous().readAttribute('id');
		lastMediaID = previousID.substring(previousID.indexOf("_")+1,previousID.length);
		$('lastMediaRow').value = lastMediaID;
	}

	if (answer !=0)
    {
 		$(ele).remove();
 	}
 }
function HandleMediaDelete(originalRequest)
{
	var text = originalRequest.responseText;
	text = text.replace(/^\s*/, '').replace(/\s*$/, '');
	alert(text);
	Element.hide(GalleyRowDeleted);
}
function DeleteGalleyList(id)
{

    answer = confirm("Do you want to delete the service?");

    if (answer !=0)
    {
    	var url = "AJAXHandler.php";
    	var pars = "module=project&func=deletePrintingService&id="+id;

    	var myAjax = new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: pars,
				onComplete: showResponse,
				onFailure: AJAXReportError
			});


    }
}

function showResponse(originalRequest)
{
	var text = originalRequest.responseText.strip();
	alert(text);
	document.location.reload();
}

/**
* Get the details of the files available in the folder
*
**/
function FileDetails()
	{
		var folderID = $('Folder').value;
		var galleyID = window.opener.document.getElementById('projid').value;
		var url = 'AJAXHandler.php';
		var pars = 'module=media&func=getFileRecord&folderID='+folderID+"&galleyID="+galleyID;

		var myAjax = new Ajax.Updater(
			'BorderBox',
			url,
			{
				method: 'get',
				parameters: pars
			});
	}

/**
* Get the details of the files available in the folder
*
**/
function NewGalleyFileDetails()
	{
		var folderID = $F('Folder');

		var url = 'AJAXHandler.php';
		var pars = 'module=media&func=getFileRecord&folderID='+folderID;

		var myAjax = new Ajax.Updater(
			'BorderBox',
			url,
			{
				method: 'get',
				parameters: pars
			});
	}

var mediaAddedToGalley = new Array();

function AddGalleyMedia()
{
	var fileID 	= GetFileCheckedValue();
	//If no value is selected, take no action
	if(fileID == null)
	{
	self.close();
	}
	//Check if the file is already added to the Galley
	if (mediaAddedToGalley.indexOf(fileID) == -1)
	{
		mediaAddedToGalley.push(fileID);
		var rowID	= window.opener.document.getElementById('galleyMediaRowCount').value;
		var url 	= 'AJAXHandler.php';
		var pars 	= 'module=media&func=addMediaToNewGalley&fileID='+fileID+'&rowID='+rowID;
		var myAjax = new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: pars,
				onComplete: AddMediaDetails,
				onFailure: AJAXReportError
			});
	} else
	{
		alert("Media file already attached to the Title");
		return false;
	}
}

//Image Resizing Help
function ImageResizingHelp()
{
	var fileID 	= GetFileCheckedValue();
	//If no value is selected, take no action
	if(fileID == null) return;

	//Check if the file is already added to the Galley
	if (mediaAddedToGalley.indexOf(fileID) == -1)
	{
		mediaAddedToGalley.push(fileID);
		var rowID	= $('galleyMediaRowCount').value;

		var url = 'AJAXHandler.php';
		var pars = 'module=media&func=addMediaToNewGalley&fileID='+fileID+'&rowID='+rowID;

		var myAjax = new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: pars,
				onComplete: AddMediaDetails,
				onFailure: AJAXReportError
			});
	} else
	{
		alert ("Media file already attached to the Title");
		return false;
	}


}

mediaAddedToGalley = new Array();
fileIDArray = new Array();

function UpdateGalleyMedia()
{
    fileIDArray = GetFileCheckedValue();

	//If no value is selected, take no action
	if(fileIDArray == null)
	{
	self.close();
	}

 /***** The following block of code is not needed as when the file is attached to galley it is not
 displayed on Add Media popup hence commenting
 by Subodh ****/

	/*Check if the file is already added to the Galley
    if (mediaAddedToGalley.indexOf(fileID) == -1)
	{
    mediaAddedToGalley.push(fileID);*/
/*********************************************/

    var galleyID= window.opener.document.getElementById('projid').value;
    var rowID	= window.opener.document.getElementById('lastMediaRow').value;
    rowID++;
    var url = 'AJAXHandler.php';
    var pars = 'module=media&func=updateMediaToGalley&fileID='+fileIDArray+'&galleyID='+galleyID+'&rowID='+rowID;

    var myAjax = new Ajax.Request(
      url,
      {
        method: 'get',
        parameters: pars,
        onComplete: UpdateMediaDetails,
        onFailure: AJAXReportError
      });

 /* The else part is also not needed hence commenting */

   /*}else
	{
		alert ("Media file already attached to the Galley");
		return false;
	}*/

 /******************/
}

function GetFileCheckedValue()
{
	var field = document.getElementsByName('FileID');
  for (var j = 0; j < field.length; j++)
	{
	  if(!($(field[j]).disabled))
	   {
		   if ($(field[j]).checked)
		    {
			   fileIDArray.push($(field[j]).value);
		    }
		 }
	}
	return fileIDArray;
}

function AddMediaDetails(originalRequest)
{
	var text 	= originalRequest.responseText;
	var fileId	= text.substr(text.indexOf('<tr id=')+8,text.indexOf('>'));
	fileId		= fileId.substr(0,fileId.indexOf('>')-1);
	var str 	= null;
	if(text.length > 0)
	{
		var winInnerHTML 	= window.opener.document.getElementById('MediaList').innerHTML;
		if(winInnerHTML.indexOf(fileId) == -1)
		{
		var tableHeader 	= winInnerHTML.substr(0,winInnerHTML.length-16);
		str = tableHeader + text + '</table>';
		window.opener.document.getElementById('MediaList').innerHTML = str;
		var currentRowID			= parseInt(window.opener.document.getElementById('galleyMediaCurrentRowCount').value);
		var rowID			= parseInt(window.opener.document.getElementById('galleyMediaRowCount').value);
		if(rowID!='0'||rowID!=null)
		 {
		   rowID = currentRowID+rowID;
     }
		window.opener.document.getElementById('galleyMediaRowCount').value = rowID;
		self.close();
		}
		else
		{
		alert('Media file already attached to the Title');
		self.close();
		}
	}
	else
	{
		self.close();
	}
}

function UpdateMediaDetails(originalRequest)
{
	var text = originalRequest.responseText;
	var str 	= null;
	if(text.length > 0)
	{
		self.close();
		window.opener.location.reload();
		var lastRow = parseInt(window.opener.document.getElementById('lastMediaRow').value);
		var winInnerHTML = window.opener.document.getElementById('MediaList').innerHTML;
		var tableHeader = winInnerHTML.substr(0,winInnerHTML.length-16);
		str = tableHeader + text + '</table>';
		window.opener.document.getElementById('MediaList').innerHTML = str;
		lastRow++;
		window.opener.document.getElementById('lastMediaRow').value = lastRow;
	}
	else
	{
		self.close();
	}
}

function RemoveMedia(fileRow,formFieldID)
{
	 answer = confirm("Do you want to remove the media file?");
	var rowIdCount = document.getElementById('galleyMediaRowCount').value;
    if (answer !=0)
    {
		var formField = 'media_'+formFieldID; //name changed from 'mfile_' to 'media_' to avoid conflict while checking duplication with reference to line no:5426	$id 	= 'media_'.$i; in function createGalley() modules/project/function.php This is fix for #2491--javascript error and to be committed with #2483 , since #2491 is found while fixing #2483.
		fileRow = 'file_'+fileRow;
		$(formField).value='';
		$(fileRow).remove();
		$(formField).remove();
		if(rowIdCount>1)
		{
			rowIdCount--;
		}
		document.getElementById('galleyMediaRowCount').value = rowIdCount;
	}

}

/////////YUI LIBRARY////////////


YAHOO.namespace("netgalley.container");

function init()
{
	YAHOO.netgalley.container.panel2 = new YAHOO.widget.Panel("panel2", { width:"500px", visible:false,draggable:false, constraintoviewport:true } );
	YAHOO.netgalley.container.panel2.render();

	YAHOO.util.Event.addListener("addMedia", "click", YAHOO.netgalley.container.panel2.show, YAHOO.netgalley.container.panel2, true);
	YAHOO.util.Event.addListener("addMediaClose", "click", YAHOO.netgalley.container.panel2.hide, YAHOO.netgalley.container.panel2, true);

	//added for image resize help
	YAHOO.netgalley.container.imgHelp = new YAHOO.widget.Panel("imgHelp", {width:"400px",visible:false,draggable:false, constraintoviewport:true,close:false} );
	YAHOO.netgalley.container.imgHelp.render();

	YAHOO.util.Event.addListener("imgResizeHelp", "click", YAHOO.netgalley.container.imgHelp.show, YAHOO.netgalley.container.imgHelp, true);
	YAHOO.util.Event.addListener("imgResizeHelp1", "click", YAHOO.netgalley.container.imgHelp.show, YAHOO.netgalley.container.imgHelp, true);
	YAHOO.util.Event.addListener("imgHelpClose", "click", YAHOO.netgalley.container.imgHelp.hide, YAHOO.netgalley.container.imgHelp, true);

}

YAHOO.util.Event.addListener(window, "load", init);

function DeleteGalley(originalRequest)
{
  text = originalRequest.responseText;
  text = text.replace(/^\s*/, '').replace(/\s*$/, '');
	//added by subodh to split text for getting active count and galley id
 var splitResult = text.split(":");
 
 var activeCount = splitResult[0];
 var galleyID = splitResult[1];
 var publicCatalogFlag = splitResult[2];
 var isActiveGalley = parseInt(publicCatalogFlag) + parseInt(activeCount);
 //added by subodh if active review count and public catalog flag is zero
 if((activeCount==0)&&(publicCatalogFlag==0))
     {
      answer = confirm(titleDeleteConfirmationMessage);
     }
  else
     {
       answer = confirm(titleActiveReviewMessage);
     }

      if (answer !=0)
        {
    	     var url = "AJAXHandler.php";
    	     var pars = "module=project&func=deleteGalley&isActiveGalley="+isActiveGalley+"&id="+galleyID;
       	   var myAjax = new Ajax.Request(
			   url,
			     {
				    method: 'get',
				    parameters: pars,
				    onComplete: Response,
				    onFailure: AJAXReportError
			     });
         }
     }

function ArchiveGalley(galleyID)
{
	answer = confirm("Do you want to archive the Title?");

    if (answer !=0)
    {
    	var url = "AJAXHandler.php";
    	var pars = "module=project&func=archiveGalley&galley="+galleyID;
       	var myAjax = new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: pars,
				onComplete: Response,
				onFailure: AJAXReportError
			});
    }
}

function Response(originalRequest)
{
	text = originalRequest.responseText;
	text = text.replace(/^\s*/, '').replace(/\s*$/, '');
	alert(text);
	window.location= "index.php?module=project&func=myGalleys";

}

function SubmitReviewReqForm()
{
		
		var ngusers = $('hiddFinalUserList').value;	
		var url = 'AJAXHandler.php?module=project&func=sendReviewRequest&type=user&ngusers='+ngusers;		
		var pars = Form.serialize('sendReviewReq');

		var myAjax = new Ajax.Request(
			url,
			{
				method: 'Post',
				parameters: pars,
				onComplete: RecordSavedReviewReq
			});
}

function RecordSavedReviewReq(originalRequest)
{
	var res = originalRequest.responseText;
	if (is.ie4 || is.ie5 || is.ie5up)
	{
		var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(res);
		var error = xmlDoc.getElementsByTagName("Error");
		var msg = xmlDoc.getElementsByTagName("Success");

	} else
	{
		// convert the string to an XML object
		var xmlobject = (new DOMParser()).parseFromString(res, "text/xml");
		var error = xmlobject.getElementsByTagName('Error');
		var msg = xmlobject.getElementsByTagName('Success');
	}

	if(msg.length >= 1)
	{
		Element.hide('systemWorking'); /* Added for #1377 : Progress Indicator - Update throughout the website*/
		alert(msg[0].firstChild.nodeValue);
		self.close();

	} else
	{
		Element.hide('systemWorking'); /* Added for #1377 : Progress Indicator - Update throughout the website*/
		alert(error[0].firstChild.nodeValue);

	}

}

function updateUserRecord(id,chk)
{
	if (chk == true)
	{
		var alreadyFormValues = Form.serialize('sendReviewReq');
			//If user record is not added to membership list add it
		if(alreadyFormValues.search(id) == -1)
		{
			var labelValue = $(id+"Label").value;
			var formValue = $(id).value;
			var formField = "<input type=\"checkbox\" id=\""+id+"\" name=\""+id+"\" value=\""+formValue+"\" checked>";
			var label =	"<label for=\""+id+"\">"+labelValue+"</label>";
			new Insertion.Bottom('MembersDetails', "<div style='margin-bottom:10px;'><span id='userRow_"+id+"'><span style='font-size:10px;margin-right:15px;'><strong>User: </strong></span><span style='font-size:10px;margin-top:5px;margin-bottom:5px;'>"+formField+"&nbsp;"+label+"</span></span></div>");
		}
	}
	else
	{
			var spanId = "userRow_"+id;
			$(spanId).remove();
	}
}

Array.prototype.getUnique = function ()
{
	var o = new Object();
	var i, e;
	for (i = 0; e = this[i]; i++) {o[e] = 1};
	var a = new Array();
	for (e in o) {a.push (e)};
	return a;
}

//Added group id to hidden value, separated by comma.
function addGroupToList(id)
{
	if($("hiddSelectedGroups").value == "")
	{
		$("hiddSelectedGroups").value = id;
	}
	else
	{
		$("hiddSelectedGroups").value = $("hiddSelectedGroups").value+","+id;
	}
	var hiddGroups = $("hiddSelectedGroups").value;
	var groupArray = hiddGroups.split(",").getUnique();
	$("hiddSelectedGroups").value = groupArray.join(",");
}

function updateGroupRecord()
{
	//clear all groups & check-uncheck final group list.
	var hiddGroups = $("hiddSelectedGroups").value;
	var groupArray = hiddGroups.split(",");
	var isEmptyTable = true;
	var groupTable = "<table border=0 cellspacing=0 cellpadding=0>";
	groupTable += "<tr><td colspan=\"2\"><strong>Recipients from your community groups:</strong></td></tr>";
	groupTable += "<tr style='height:10px;'><td colspan=\"2\"></td></tr>";
	groupTable += "<tr><td width='200'><u>Name</u></td><td><u>Group</u></td></tr>";
	groupTable += "<tr style='height:10px;'><td colspan=\"2\"></td></tr>";
	for(i=0; i<groupArray.length; i++)
	{
			var id = groupArray[i];
			var selectedID = "GROUP"+id;
			var checkedID = "chkGROUP"+id;
			if(id != "")
			{
			if ($(selectedID).checked == true)
			{
				if($(checkedID) == null) //insert new span
				{
					var labelValue = $(selectedID+"Label").value;
					var formValue = $(selectedID).value;
					var formField = "<input type=\"checkbox\" id=\""+checkedID+"\" name=\""+checkedID+"\" value=\""+formValue+"\"  checked=\"checked\" onClick=\"removeGroup("+id+");\">";
					var label =	"<label for=\""+checkedID+"\">"+labelValue+"</label>";
					new Insertion.Bottom('MembersDetails', "<div style='margin-bottom:10px;'><span id='groupRow_"+id+"'><span style='font-size:10px;margin-right:8px;'><strong>Group: </strong></span><span style='font-size:10px;margin-top:5px;margin-bottom:5px;padding-left:5px;'>"+formField+"&nbsp;"+label+"</span></span></div>");

					var userArray = eval("arrayUserOfGroup" + id);
					groupTable += "<tr id='groupTableRow_"+id+"'><td colspan=\"2\">";
					groupTable += "<table border=0 id=\"tblGroupPreview"+id+"\" width=\"100%\" cellspacing=0 cellpadding=0>";
					for(x=0; x<userArray.length; x++)
					{
						var groupUserName = userArray[x];
						groupTable += "<tr><td width='200'>"+groupUserName+"</td><td>"+labelValue+"</td></tr>";
						groupTable += "<tr style='height:10px;'><td colspan=\"2\"></td></tr>";
					}
					groupTable += "</table>";
					groupTable += "</td></tr>";
				}
			    else //checked, if checkbox is checked
				{
					$(checkedID).checked = true;
				}
				isEmptyTable = false;
			}
			else //remove the span, if checkbox is unchecked
			{
				var spanId = "groupRow_"+id;
				if( $(spanId) != null)
				$(spanId).remove();
			}
			}
	}

	groupTable +="</table>";
	//if groups are not selected.
	if(isEmptyTable)
	{
		groupTable = "";
	}
	$('divCommunityGroups').innerHTML = groupTable;

	Element.hide('AddGroup');
	Element.show('MainBlock');
}

function removeGroup(id)
{
	$('GROUP'+id).checked = $("chkGROUP"+id).checked;
	if($("chkGROUP"+id).checked)
	{
		setDisplayProperty($('tblGroupPreview'+id),'');
	}
	else
	{
		setDisplayProperty($('tblGroupPreview'+id),'none');
	}

	if(isGroupPreviewEmpty())
	{
		setDisplayProperty($('divCommunityGroups'),'none');
	}
	else
	{
		setDisplayProperty($('divCommunityGroups'),'');
	}
}

function isGroupPreviewEmpty()
{
	var hiddGroups = $("hiddSelectedGroups").value;
	var groupArray = hiddGroups.split(",");
	for(i=0; i<groupArray.length; i++)
	{
		var id = groupArray[i];
		var checkedID = "chkGROUP"+id;
		if($(checkedID) != null)
		{
			if($(checkedID).checked)
			{
				return false;
			}
		}
	}
	return true;
}

function PreviewRequest()
{
  //Modified by Subodh
	Element.hide('MainBlock');
	//if ($F("pubCustomMessage") == "")
	//{
		var url = 'AJAXHandler.php';
		var pars = 'module=project&func=emailMsgForPreview';

		var myAjax = new Ajax.Updater(
			'MessageBlock',
			url,
			{
				method: 'get',
				parameters: pars,
				onFailure: AJAXReportError
			});
	//} else
	//{
		//res = "<img border=\"0\" src=\"http://www.netgalley.com/images/hdr_logo.jpg\" width=\"631\" height=\"94\"></p>";
		//res += $F("pubCustomMessage");
		//res += "<br /><br /><center><a href=\"#\" onClick=\"Element.show('MainBlock'); Element.hide('MessageBlock');\">Close Preview</a></center>"
		//$('MessageBlock').innerHTML = res;
	//}

	Element.show('MessageBlock');
}

function DeleteInvitation(row,invID)
{
	answer = confirm("Do you want to archive this invitation?");

    if (answer !=0)
    {
		var url = 'AJAXHandler.php';
		var pars = 'module=project&func=archivedInvitation&invitationID='+invID;

		var myAjax = new Ajax.Request(
			url,
			{
				method: 'Post',
				parameters: pars,
				onComplete: DeleteInvitationResponse,
				onFailure: AJAXReportError
			});
    }
}

function DeleteInvitationResponse(originalRequest)
{
	text = originalRequest.responseText;
	text = text.replace(/^\s*/, '').replace(/\s*$/, '');
	alert(text);
	window.location.reload();

}
/*
* Displays details on the dashboard
*/
function DisplayDetails(id)
{
	images = document.getElementsByTagName('img');
	for ( var i = 0; i < images.length; i++)
	{
		if(images[i].getAttribute('id') == id)
		{
			images[i].setAttribute('src','images/blk_arrow_down.gif') ;

		}
	}
	ele = document.getElementsByName("CompletedReviewDiv");

	for (i = 0; i < ele.length; i++)
	{
		document.getElementsByName("CompletedReviewDiv")[i].style.display = '';
	}
}

function ApproveReview()
{
	answer = confirm("Do you want to approve the review for publication?");

    if (answer !=0)
    {
		var formVal = Form.serialize('approveReview');
		var url = 'AJAXHandler.php';
		var pars = 'module=project&func=reviewApproval&'+formVal;
		var myAjax = new Ajax.Request(
			url,
			{
				method: 'Post',
				parameters: pars,
				onComplete: ShowStatus,
				onFailure: AJAXReportError
			});

		return true;
    } else
    {
    	return false;
    }
}
function ShowStatus(originalRequest)
{
	text = originalRequest.responseText;
	text = text.replace(/^\s*/, '').replace(/\s*$/, '');
	alert(text);

}
CreateCalendar = function(id)
{
	Calendar.setup({inputField:id,ifFormat:'%m/%d/%Y'});
}

function HandleImageUpload(url)
{
	answer = confirm("Have you saved your title? If not, click Cancel and Save your title\n before uploading an image.");

    if (answer ==0)
    {
    	$('editGalleyDisplay').value='1';
    	document.editGalley.submit();
    } else
    {
		$('editGalleyDisplay').value='0';
		window.open(url,'popuppage','width=510,scrollbars=yes,height=170,top=100,left=150');
    }
}

//to check upload image type
function check(obj){
	var filename  = obj;
	var a = filename.substr(filename.length-4,4);

	if (a == ".jpg" || a == ".JPG" || a == ".gif" || a == ".GIF" || a == ".png" || a == ".PNG"){
		return true;
	}
	else
	{
		return false;
	}
}

/** Function to check the numeric data */

function IsNumeric(sText)
{
	var ValidChars = "0123456789.";
	var IsNumber=1;
	var Char;
   for (i = 0; i < sText.length && IsNumber == 1; i++)
   {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
      {
         IsNumber = 0;
      }
    }
   return IsNumber;
}

/** Function to check the ISBN */

function checkISBN(sText)
{
var alphaNumChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var specialChar = "-";
var IsISBN=1;
var totalChar = 0;
var prevChar = "";
var Char;
	for (i = 0; i < sText.length && IsISBN == 1; i++)
      {
      Char = sText.charAt(i);
	  if (alphaNumChars.indexOf(Char) == -1)
		 {
			 if (specialChar.indexOf(Char) == -1)
			 {
				IsISBN = 0;
				break;
			 }
			 else
			 {
				if(prevChar == Char || i == 0 || i == sText.length-1)
				{
					IsISBN = 0;
					break;
				}
			 }
		 }
		else
		{
			totalChar++; // counts total no. of alpha num characters.
		}
		prevChar = Char; // set previous char
      }
if (totalChar > 13) // max alpha num char will be 13.
	{
		IsISBN = 2;
	}
   return IsISBN;
}

function isbnIsValid(isbn)
{
	var alphaNumChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var ch;

	isbn = isbn.replace(/-/g, "");
	
	if (isbn.length != 13)
		return false;
		
	for (i = 0; i < isbn.length; i++)
    {
    	ch = isbn.charAt(i);
    	if (alphaNumChars.indexOf(ch) == -1)
	  		return false;
	}
	
	return true;
}

/**--------------------------
//* Validate Date Field script- By JavaScriptKit.com
//* For this script and 100s more, visit http://www.javascriptkit.com
//* This notice must stay intact for usage
---------------------------**/
function checkdate(input)
{
	var validformat=/^\d{2}\/\d{2}\/\d{4}$/; //Basic check for format validity
	var returnval=false;
	if (!validformat.test(input.value))
	{
		return false;
	} else
	{ //Detailed check for valid date ranges
		var yearfield=input.value.split("/")[2];
		var monthfield=input.value.split("/")[0];
		var dayfield=input.value.split("/")[1];
		var dayobj = new Date(yearfield, monthfield-1, dayfield);

		if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
			return false;
			else
			return true;
	}
}

function validateGalleyDetails(formType)
{
	//alert('validateGalleyDetails('+formType+')');
	var title = trim($("titletext").value);
	var galleyIsbn = trim($("isbn").value);
	//for #2392 >> validations added to allow plain text only.
	
	var cat_list = $('CatgTable').innerHTML;
	cat_list = cat_list.toLowerCase();
	//Check the date
	if (!$('PubDate').value.blank()) 
	{
		if (!checkdate($('PubDate'))) 
		{
			alert("Invalid date! Should be in MM/DD/YYYY format");
			$('PubDate').focus();
			return false;
		}
	}
    if(formType=='editGalley')
        {
            var catalogText = trim($("catalogText").value);
            if(catalogText.match(/([\<])([^\>]{1,})*([\>])/i)!=null) //check all html tags
            {
                alert("Please remove HTML tags from your catalog text by clicking REMOVE HTML TAGS."); //fix for #2392
                $('catalogText').focus();
                return false;
            }
        }
	if (title == "") 
	{
		alert("Please enter Galley Title before saving");
		$("titletext").focus();
		return false;
	}

	if (!isbnIsValid(galleyIsbn))
	{
		alert('Please enter a 13-digit ISBN without hyphens.');
		$('isbn').focus();
		return false;
	}
		
	/* Check the print formats data */
	//alert($('totalPrintEditions').value);
	for (j = 1; j <= $('totalPrintEditions').value; j++) 
	{
		//alert("printEdition "+j);
		page = 'printPages_' + j;
		price = 'printPrice_' + j;
		date = 'printDate_' + j;

		if (IsNumeric($(page).value) == 0) 
		{
			alert('Invalid page number.');
			$(page).focus();
			return false;
		}
		if (IsNumeric($(price).value) == 0) 
		{
			alert('Invalid price.');
			$(price).focus();
			return false;
		}

		//Check the date
		if (!$(date).value.blank()) 
		{
			if (!checkdate($(date))) 
			{
				alert("Invalid date! Should be in MM/DD/YYYY format");
				$(date).focus();
				return false;
			}
		}
	}

	/* Check the audio formats data */
	for (j = 1; j <= $('totalAudioEditions').value; j++) 
	{
		price = 'audioPrice_' + j;
		date = 'audioDate_' + j;

		if (IsNumeric($(price).value) == 0) 
		{
			alert('Invalid price.');
			$(price).focus();
			return false;
		}

		//Check the date
		if (!$(date).value.blank()) 
		{
			if (!checkdate($(date))) 
			{
				alert("Invalid date! Should be in MM/DD/YYYY format");
				$(date).focus();
				return false;
			}
		}
	}

	/* Check the eBook formats data */
	for (j = 1; j <= $('totaleBookEditions').value; j++) 
	{
		price = 'eBookPrice_' + j;
		eBookSize = 'eBookSize_' + j;
		date = 'eBookDate_' + j;

		if (IsNumeric($(price).value) == 0) 
		{
			alert('Invalid price.');
			$(price).focus();
			return false;
		}

		var regE = /^([0-9])+(((\.)?([0-9])+)|(([0-9])*))([\s])*([a-zA-Z])*$/;
		if (!$(eBookSize).value.blank()) 
		{
			if (!regE.test(trim($(eBookSize).value))) 
			{
				alert('Invalid size.');
				$(eBookSize).focus();
				return false;
			}
		}

		//Check the date
		if (!$(date).value.blank()) 
		{
			if (!checkdate($(date))) 
			{
				alert("Invalid date! Should be in MM/DD/YYYY format");
				$(date).focus();
				return false;
			}
		}
	}

	//Url
	for (var i = 1; i <= $('totalUrls').value; i++) 
	{
		//trimming values
		$('desc_' + i).value = trim($('desc_' + i).value);
		$('link_' + i).value = trim($('link_' + i).value);

		if ($('desc_' + i).value.blank() && !$('link_' + i).value.blank()) 
		{
			alert("Please enter Description.");
			$('desc_' + i).focus();
			return false;
		}
		if (!$('desc_' + i).value.blank() && $('link_' + i).value.blank()) 
		{
			alert("Please enter Web Link.");
			$('link_' + i).focus();
			return false;
		}
		if(!$('link_' + i).value.blank() && !isValidWebLink($('link_' + i).value, i))
		{
			alert("Please enter a valid Web Link (http://www.website.com)");
			$('link_' + i).focus();
			return false;
		}

	}


	//Contributor
	for (var i = 1; i <= $('totalContributors').value; i++) 
	{
		if ($('contributor_' + i).value.blank() && !$('cont_role_' + i).value.blank()) 
		{
			alert("Contributor name missing.");
			$('contributor_' + i).focus();
			return false;

		}
		if (!$('contributor_' + i).value.blank() && $('cont_role_' + i).value.blank()) 
		{
			alert("Please select Contributor role.");
			$('cont_role_' + i).focus();
			return false;
		}
	}

	if (formType == "newGalley") 
	{
		if ($("thumbnailImage-file-path").value != "") 
		{
			CoverImage = $("thumbnailImage-file-path").value;
			if (!check($("thumbnailImage-file-path").value)) 
			{
				alert("Cover image is an unsupported file type, please use a JPG or GIF file type.");
				$("thumbnailImage-file-path").focus();
				return;
			}
		}
		if ($("authorImage-file-path").value != "") 
		{
			if (!check($("authorImage-file-path").value, "Author Image")) 
			{
				alert("Author image is an unsupported file type, please use a JPG or GIF file type.");
				$("authorImage-file-path").focus();
				return;
			}
		}
	}
	else if (document.editGalley.publicView.checked)
	{
		Author = document.editGalley.Author.value;
		Publisher = document.editGalley.Publisher.value;
		CoverImage = document.editGalley.CoverImage.value;
		pubDate = document.editGalley.PubDate.value;
		var isAnyReadingOptionSelected = document.editGalley.isAnyReadingOptionSelected.value;
		if (Author == "" || Publisher == "" || CoverImage =="" || pubDate =="" || isAnyReadingOptionSelected=='f') 
		{
			alert(publicCatalogValidation);
			document.editGalley.publicView.checked = false;
			for (i = 0; i <= 2; i++) 
			{
				document.editGalley.galleyAccess[i].checked = false;
			}
			return;
		}
	}
	
	var url = "AJAXHandler.php?module=project&func=isbnCheck";
	var projectId = 0;
	if (formType == "editGalley")
		var projectId = $('projid').value;

	var args = "isbn="+ galleyIsbn + "&formType=" + formType + "&projectId=" + projectId;
		
	new Ajax.Request( url,
					{ method: 'post',
					  parameters: args,
					  onComplete: submitGalleyForm
					  });
}

function submitGalleyForm(originalRequest)
{
	var response = originalRequest.responseText;
	//alert('submitGalleyForm: '+response);
	var start = response.indexOf('{{{');
	var stop = response.indexOf('}}}');
	response = response.substring(start+3, stop);
	//alert(response);
	var parts = response.split(",");
	formType = parts[0];
	returnFlag = parts[1];
	if (returnFlag != "valid")
	{
		alert("The ISBN you've entered is in use by another title.  Please enter an ISBN that is unique to this title.");
		$('isbn').focus();
		return false;
	}

	if (formType == "newGalley") 
		document.CreateGalley.submit();
	else if (formType == "editGalley") 
		document.editGalley.submit();
}

function isValidWebLink(link, i)
{
	if(link.substring(0,7).toLowerCase() != "http://" && link.substring(0,8).toLowerCase() != "https://")
	{
		link = "http://" + link;
	}
	var regexp1 = /^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-zA-Z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/;
	if (!regexp1.test(link))
	{
		return false;
	}
	$('link_' + i).value = link;	//attached "http://" value to link before saving
	return true;
}

//to trim the string
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function DeleteCatg(catg,id)
{
	answer = confirm("Do you want to remove the Subject Category?");

    if (answer !=0)
    {
		var url = "AJAXHandler.php?module=project&func=deleteCatg";
		var args = "catg="+catg+"&id="+id;
		new Ajax.Request( url,
						{ method: 'post',
						  parameters: args,
						  onComplete: ConfirmationMsg
						  });
    }
}
function ConfirmationMsg(originalRequest)
{
	var res = originalRequest.responseText;
	res = res.replace(/^\s+|\s+$/g, '');
	alert(res);
	window.location.reload();
}
//Added by Subodh 24/12/2007
function getOrganization()
{
	document.getElementById("tabIndex").value = 0;
    var Obj = document.sendReviewReq.radFRO;
    for (var i=0; i < Obj.length; i++)
        {
            if (Obj[i].checked)
            {
                 var id = Obj[i].value;
            }
        }

    //alert(Obj);
	//var selIndex = Obj.selectedIndex;
	//var id = Obj.options[selIndex].value;
    
	if(id=="")
	  {
		   //alert("Please select Featured Review Organization");
		   return false;
	  }
	var url = "AJAXHandler.php";
	var pars = "module=project&func=getSubmissionCategories&id="+id;
	var myAjax = new Ajax.Request(
			url,
			{
				method: 'Post',
				parameters: pars,
				onComplete: dispResponse,
				onFailure: AJAXReportError
			});
}
//***************************

//Added by Subodh 26/12/2007
function dispResponse(originalRequest)
{
	var res = originalRequest.responseText.strip();
    //alert(res);
	$('lstSubmission').options.length = 0;
	if (is.ie4 || is.ie5 || is.ie5up)
	{
		var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(res);
        var RecordFlagTag = xmlDoc.getElementsByTagName("SqlResult");
        var RecordFlag = RecordFlagTag[0].firstChild.nodeValue;
          if(RecordFlag=='Yes')
           {
            var FroIdTag = xmlDoc.getElementsByTagName("FroId");
            var Address1 = xmlDoc.getElementsByTagName("Address");
            var Address2 = xmlDoc.getElementsByTagName("Address2");
            var City = xmlDoc.getElementsByTagName("City");
            var State = xmlDoc.getElementsByTagName("State");
            var Country = xmlDoc.getElementsByTagName("Country");
            var Zip = xmlDoc.getElementsByTagName("Zip");
            var GuideLine = xmlDoc.getElementsByTagName("GuideLine");
            var Name = xmlDoc.getElementsByTagName("Name");
            var PrintGalley = xmlDoc.getElementsByTagName("PrintGalley");
            var PrintGalleyInfo = xmlDoc.getElementsByTagName("PrintGalleyInfo");
            var Counter = xmlDoc.getElementsByTagName("Counter");
            var Count = Counter[0].firstChild.nodeValue;
            for(i=0;i<Count;i++)
				{
					var elementN = "CatName"+i;
					var elementID = "CatID"+i;
					var Counter = xmlDoc.getElementsByTagName(elementN);
					var CounterID = xmlDoc.getElementsByTagName(elementID);
					var catCounterN = Counter[0].firstChild.nodeValue;
					var catCounterID = CounterID[0].firstChild.nodeValue;
					$('lstSubmission').options[i] = new Option( catCounterN,catCounterID);
				}
            var FroId = FroIdTag[0].firstChild.nodeValue;
            var add1 = Address1[0].firstChild.nodeValue;
            var add2 = Address2[0].firstChild.nodeValue;
            var city_name = City[0].firstChild.nodeValue;
            var state_name = State[0].firstChild.nodeValue;
            var country_name = Country[0].firstChild.nodeValue;
            var zipp = Zip[0].firstChild.nodeValue;
            var GuideLine = GuideLine[0].firstChild.nodeValue;
            var PrintGalle = PrintGalley[0].firstChild.nodeValue;
            var PrintGalleInfo = PrintGalleyInfo[0].firstChild.nodeValue;
            var Name = Name[0].firstChild.nodeValue;

            document.getElementById('orgId').value = FroId;
            document.getElementById('SubmissionNotes').innerHTML= "Please add any relevant notes that you would like to communicate to"+" "+Name;
            document.getElementById('guideLineTitle').innerHTML= "Please take note of the following submission guidelines for"+" "+Name;
            if(PrintGalleInfo=='NA')
            {
			  PrintGalleInfo = "";
            }
            if(add2=='NA')
            {
			  var address = add1+"\n"+city_name+","+state_name+","+country_name+","+zipp;
            }
            else
            {
		     var address = add1+"\n"+add2+"\n"+city_name+","+state_name+","+country_name+","+zipp;
            }
            document.getElementById('txtAddress').value = address;
            document.getElementById('GuideLine').innerHTML = GuideLine;
            if(PrintGalle == 'f')
            {
			 if(PrintGalleInfo == "")
                {
                    document.getElementById('cnfPhysicalGalley').innerHTML = "No";
                    document.getElementById('galleyRequired').innerHTML = "No";
                }
			else
                {
                    document.getElementById('cnfPhysicalGalley').innerHTML = "No"+" ("+PrintGalleInfo+")";
                    document.getElementById('galleyRequired').innerHTML = "No"+" ("+PrintGalleInfo+")";
                }

			document.getElementById('phyGalley').style.color ='#cccccc';
			document.getElementById('pubShipInfo').style.color ='#cccccc';
			document.getElementById('shipServ').style.color ='#cccccc';
			document.getElementById('trackNo').style.color ='#cccccc';
			document.getElementById('exTrack').style.color ='#cccccc';
			document.getElementById('lstShippingService').disabled =true;
			document.getElementById('txtTracking_number').disabled =true;
			document.getElementById('txtAddress').disabled =true;
		}
		else
		{
			 if(PrintGalleInfo == "")
			 {
			 	document.getElementById('cnfPhysicalGalley').innerHTML = "Yes";
				document.getElementById('galleyRequired').innerHTML = "Yes";
			 }
			 else
			 {
			 	document.getElementById('cnfPhysicalGalley').innerHTML = "Yes"+" ("+PrintGalleInfo+")";
				document.getElementById('galleyRequired').innerHTML = "Yes"+" ("+PrintGalleInfo+")";
			 }
			 document.getElementById('phyGalley').style.color ='#000000';
			 document.getElementById('pubShipInfo').style.color ='#000000';
			 document.getElementById('shipServ').style.color ='#000000';
			 document.getElementById('trackNo').style.color ='#000000';
			 document.getElementById('exTrack').style.color ='#000000';
			 document.getElementById('lstShippingService').disabled =false;
			 document.getElementById('txtTracking_number').disabled =false;
			 document.getElementById('txtAddress').disabled =false;
		}
		document.getElementById('cnfReviewOrg').innerHTML = Name;
    }
 } else
	{
		// convert the string to an XML object
		var xmlobject = (new DOMParser()).parseFromString(res, "text/xml");
            RecordFlagTag = xmlobject.getElementsByTagName("SqlResult");
            RecordFlag = RecordFlagTag[0].firstChild.nodeValue;
          if(RecordFlag=='Yes')
           {
            Name = xmlobject.getElementsByTagName("Name");
            FroIdTag = xmlobject.getElementsByTagName("FroId");
            Address1 = xmlobject.getElementsByTagName("Address");
            Address2 = xmlobject.getElementsByTagName("Address2");
            City = xmlobject.getElementsByTagName("City");
            State = xmlobject.getElementsByTagName("State");
            Country = xmlobject.getElementsByTagName("Country");
            Zip = xmlobject.getElementsByTagName("Zip");
            GuideLine = xmlobject.getElementsByTagName("GuideLine");
            PrintGalley = xmlobject.getElementsByTagName("PrintGalley");
            PrintGalleyInfo = xmlobject.getElementsByTagName("PrintGalleyInfo");
            Counter = xmlobject.getElementsByTagName("Counter");
            Count = Counter[0].firstChild.nodeValue;

            for(i=0;i<Count;i++)
				{
					elementN = "CatName"+i;
					elementID = "CatID"+i;
					Counter = xmlobject.getElementsByTagName(elementN);
					CounterID = xmlobject.getElementsByTagName(elementID);
					catCounterN = Counter[0].firstChild.nodeValue;
					catCounterID = CounterID[0].firstChild.nodeValue;
					document.getElementById('lstSubmission').options[i] = new Option( catCounterN,catCounterID);
				}
                 FroId = FroIdTag[0].firstChild.nodeValue;
				 add1 = Address1[0].firstChild.nodeValue;
	 			 add2 = Address2[0].firstChild.nodeValue;
				 city_name = City[0].firstChild.nodeValue;
				 state_name = State[0].firstChild.nodeValue;
				 country_name = Country[0].firstChild.nodeValue;
				 zipp = Zip[0].firstChild.nodeValue;
	 			 GuideLine = GuideLine[0].firstChild.nodeValue;
				 Name = Name[0].firstChild.nodeValue;
				 PrintGalle = PrintGalley[0].firstChild.nodeValue;
				 PrintGalleInfo = PrintGalleyInfo[0].firstChild.nodeValue;
				 if(add2=='NA')
		  			{
                        address = add1+"\n"+city_name+","+state_name+","+country_name+","+zipp;
		 		 	}
				else
					{
                         address = add1+"\n"+add2+"\n"+city_name+","+state_name+","+country_name+","+zipp;
					}
                 document.getElementById('orgId').value = FroId;
	 			 document.getElementById('txtAddress').value = address;
	             document.getElementById('GuideLine').innerHTML = GuideLine;
				 PrintGalleInfo = PrintGalleyInfo[0].firstChild.nodeValue;

				 document.getElementById('SubmissionNotes').innerHTML= "Please add any relevant notes that you would like to communicate to"+" "+Name;
				 document.getElementById('guideLineTitle').innerHTML= "Please take note of the following submission guidelines for"+" "+Name;

				 if(PrintGalleInfo=='NA')
		  	 	 {
			  		PrintGalleInfo = "";
		  	 	 }
				 if(PrintGalle == 't')
				 {
					if(PrintGalleInfo == "")
					{
						document.getElementById('cnfPhysicalGalley').innerHTML = "Yes";
						document.getElementById('galleyRequired').innerHTML = "Yes";
					}
					else
					{
						document.getElementById('cnfPhysicalGalley').innerHTML = "Yes"+" ("+PrintGalleInfo+")";
						document.getElementById('galleyRequired').innerHTML = "Yes"+" ("+PrintGalleInfo+")";
					}
					 // change field style
					 document.getElementById('phyGalley').style.color ='#000000';
					 document.getElementById('pubShipInfo').style.color ='#000000';
					 document.getElementById('shipServ').style.color ='#000000';
					 document.getElementById('trackNo').style.color ='#000000';
					 document.getElementById('exTrack').style.color ='#000000';
					 document.getElementById('lstShippingService').disabled =false;
					 document.getElementById('txtTracking_number').disabled =false;
					 document.getElementById('txtAddress').disabled =false;
				 }
				 else
				 {
					if(PrintGalleInfo == "")
					{
						document.getElementById('cnfPhysicalGalley').innerHTML = "No";
						document.getElementById('galleyRequired').innerHTML = "No";
					}
					else
					{
						document.getElementById('cnfPhysicalGalley').innerHTML = "No"+" ("+PrintGalleInfo+")";
						document.getElementById('galleyRequired').innerHTML = "No"+" ("+PrintGalleInfo+")";
					}
					//gray out fields
					document.getElementById('phyGalley').style.color ='#cccccc';
					document.getElementById('pubShipInfo').style.color ='#cccccc';
					document.getElementById('shipServ').style.color ='#cccccc';
					document.getElementById('trackNo').style.color ='#cccccc';
					document.getElementById('exTrack').style.color ='#cccccc';
					document.getElementById('lstShippingService').disabled =true;
					document.getElementById('txtTracking_number').disabled =true;
					document.getElementById('txtAddress').disabled =true;
				}
      }
	}

	 return true;
}
function sendOrgRequest()
{

	answer = confirm("You are about to send a request to review " +$("galleyTitle").value+ "\n Click OK to continue.");

    if (answer !=0)
    {
		var url = 'AJAXHandler.php?module=project&func=sendOrganizationReviewRequest';
		var pars = Form.serialize('sendReviewReq');

		var myAjax = new Ajax.Request(
			url,
			{
				method: 'Post',
				parameters: pars,
				onComplete: RecordSavedOrgReq
			});
	}
}

/*
function saveRFRCustomEmail()
{

	answer = confirm("You are about to save a Request for Review Email" +$("email_id").value+ "\n Click OK to continue.");

    if (answer !=0)
    {
		var url = 'AJAXHandler.php?module=project&func=saveRFREmail';
		var pars = Form.serialize('sendReviewReq');

		var myAjax = new Ajax.Request(
			url,
			{
				method: 'Post',
				parameters: pars,
				onComplete: RecordSavedOrgReq
			});
	}
}
*/
function RecordSavedOrgReq(originalRequest)
{
	var res = originalRequest.responseText;
	if (is.ie4 || is.ie5 || is.ie5up)
	{
		var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(res);
		var error = xmlDoc.getElementsByTagName("Error");
		var msg = xmlDoc.getElementsByTagName("Success");

	} else
	{
		// convert the string to an XML object
		var xmlobject = (new DOMParser()).parseFromString(res, "text/xml");
		var error = xmlobject.getElementsByTagName('Error');
		var msg = xmlobject.getElementsByTagName('Success');
	}

	if(msg.length >= 1)
	{
		alert(msg[0].firstChild.nodeValue);
		self.close();

	} else
	{
		alert(error[0].firstChild.nodeValue);

	}

}

//added by pravin
function isAlphNum(strValue)
{
	var objRegExp  = /^[a-zA-Z0-9\.\-\& ]*$/;
	return objRegExp.test(strValue);
}
function isValidTrackingNo(strValue)
{
	var objRegExp  = /^[a-zA-Z0-9\.\,\;\?\#\&\-\'\" ]*$/;
	return objRegExp.test(strValue);
}
function onlyNum(strValue)
{
	var objRegExp  = /^[0-9]*$/;
	return objRegExp.test(strValue);
}

/*
function validURL(strValue)
{
		//var regexp = /^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([\w]+)(.[\w]+){1,2}$/;
		//var regexp1 = /^(((http))\:\/\/)(www)+\.[a-zA-Z0-9\-\.]+\.(aero|biz|com|edu|gov|info|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|us|fr)(\/)+[a-zA-Z0-9\-\.]+(\:[0-9]+)*$/;
		var regexp1 = /^((((h|H)(t|T)(t|T)(p|P)))\:\/\/)(w|W){3}\.[a-zA-Z0-9\-\.]+\.([a-zA-Z])+(\/)?((\/)?([a-zA-Z0-9\-\.]+))*(\:[0-9]+)*$/;

		regexp1.test(strValue);
		return regexp1.test(strValue);
}
*/

//date validate function
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
	for (i = 0; i < s.length; i++){
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}


function stripCharsInBag(s, bag){
	var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++){
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
	// EXCEPT for centurial years which are not also divisible by 400.
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("Invalid date! Please enter the publication date MM/DD/YYYY format")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Invalid date! Please enter the publication date MM/DD/YYYY format")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Invalid date! Please enter the publication date MM/DD/YYYY format")
		return false
	}
return true
}

function MyGalleySearchField()
{
	var sortField = document.getElementById("Type");
  	var searchOption = sortField .options[sortField .selectedIndex].text;
	var searchText = document.getElementById('search').value;
	if(document.myGalleySearch.search.value== '-- Search --' || document.myGalleySearch.search.value.length == 0)
	{
		alert('Please enter the search criteria');
		return false
	}
	else if((searchOption=="Pub Date")&&(isDate(searchText)==false))
	{
		return false;
	}
	else {
		return true;
	}
}

function PrintDialog()
{
	 var printContent 	= document.getElementById("Boxes");
	 var windowUrl 		= 'about:blank';
	 var printWindow 	= window.open(windowUrl, 'ONIXError', 'left=200,top=0,width=500,height=200,scrollbar=yes');
	 printWindow.document.write(printContent.innerHTML);
	 printWindow.document.close();
	 printWindow.focus();
	 printWindow.print();
	 printWindow.close();
}
//************************************************************
//added by subodh for calling php function to check active reviews.
function CheckActiveReview(galleyID)
{
 		var url = 'AJAXHandler.php';
    	var pars = "module=project&func=checkActiveReview&id="+galleyID;
       	var myAjax = new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: pars,
				onComplete: DeleteGalley,
				onFailure: AJAXReportError
			});
}

//check uncheck for community users
function checkUncheckAll()
{
	var i;
	for(i=0; i<$('hid_totalCnt').value; i++)
	{
		var chkRequest = $("userCheck_" + $('UID'+i).value);
		chkRequest.checked = $('checkUncheck').checked;
	}
}

//uncheck when any check box is clicked
function uncheckMain(chkRequest)
{
	if(!chkRequest.checked)
	{
		$('checkUncheck').checked = false;
	}
	else
	{
		var flag = ""; // "checkbox_unchecked";
		for(k=0; k<$('hid_totalCnt').value; k++)
		{
			var chkRequest = $("userCheck_" + $('UID'+k).value);
			if(!chkRequest.checked)
			{
			flag = "checkbox_unchecked";
			break;
			}
		}
		if(flag == "checkbox_unchecked")
		{
			$('checkUncheck').checked = false;
		}
		else
		{
			$('checkUncheck').checked = true;
		}
	}
}

//add my community user
function addMyCommunityUsers()
{
	//clear all community members
	for(i=0; i<$('hid_totalCnt').value; i++)
	{
			var spanId = "userRow_"+i;
			if( $(spanId) != null)
			$(spanId).remove();
	}

	var isEmptyTable = true;
	var communityTable = "<table border=0 cellspacing=0 cellpadding=5>";
	communityTable += "<tr><td colspan=\"2\"><strong>Recipients from your community:</strong></td></tr>";
	communityTable += "<tr><td width='200'><u>Name</u></td><td><u>Company</u></td></tr>";
	for(i=0; i<$('hid_totalCnt').value; i++)
	{
		var chkUser = $("userCheck_" + $('UID'+i).value);
		if(chkUser.checked == true)
		{
			var id = $("UID" + i).value;
			var uid = "checkedUser"+id;
			var fieldName = "USER"+id;
			var userEmail = $(fieldName).value;
			var compName = $("COMPANY"+id).value;
			var label = $("USER"+id+"Label").value;
			var alreadyFormValues = Form.serialize('sendReviewReq');
			isEmptyTable = false;

			//If user record is not added to membership list add it
			if(!isUserIdExists(id))
			{
				var formField = "<input type=\"hidden\" id=\""+uid+"\" name=\""+uid+"\" value=\""+id+"\" ><input type=\"checkbox\" id=\""+fieldName+"\" name=\""+fieldName+"\" value=\""+userEmail+"\" checked=\"checked\" onClick=\"removeCommunityUser("+id+");\">";	
				
				new Insertion.Bottom('MembersDetails', "<div style='margin-bottom:10px;'><span id='userRow_"+i+"'><span style='font-size:10px;margin-right:15px;'><strong>User: </strong></span><span style='font-size:10px;margin-top:5px;margin-bottom:5px;padding-left:5px;'>"+formField+" "+label+"</span></span></div>");
			}
			communityTable += "<tr id='communityUserRow"+id+"'><td>"+label+"</td><td>"+compName+"</td></tr>";
		}
		else
		{
			var spanId = "userRow_"+i;
			if( $(spanId) != null)
			$(spanId).remove();
		}
	}
	communityTable +="</table>";
	//if users are not selected.
	if(isEmptyTable)
	{
		communityTable = "";
	}
	$('communityUsers').innerHTML = communityTable;
	Element.hide('MyCommunity');Element.show('MainBlock');
}

function isUserIdExists(id)
{
	if($('checkedUser'+id) != null)
	{
		if($('checkedUser'+id).value == id)
		return true;
	}
	return false;
}

function removeCommunityUser(id)
{
	if($("USER"+id).checked == true)
	{
		$('userCheck_'+id).checked = true;
		setDisplayProperty($('communityUserRow'+id),'');
	}
	else
	{
		$('userCheck_'+id).checked = false;
		setDisplayProperty($('communityUserRow'+id),'none');
	}

	if(isCommunityUserPreviewEmpty())
	{
		setDisplayProperty($('communityUsers'),'none');
	}
	else
	{
		setDisplayProperty($('communityUsers'),'');
	}
}

function isCommunityUserPreviewEmpty()
{
	for(i=0; i<$('hid_totalCnt').value; i++)
	{
		var id = $("UID" + i).value;
		var fieldName = "USER"+id;
		if($(fieldName) != null)
		{
			if($(fieldName).checked)
			{
				return false;
			}
		}
	}
	return true;
}

/*
//for non NG members
function nonNGMembers()
{
	if(!validateEmail())
	{
		return false;
	}
	else
	{
		var str= document.getElementById('csvFileData').value;
		emailArr=str.split(";").getUnique();
		var isEmptyTable = true;

		//clear all community members
		for(i=0; i<$('hid_emailCnt').value; i++)
		{
			var spanId = "emailRow_"+i;
			if( $(spanId) != null)
			$(spanId).remove();
		}
		$('hid_emailCnt').value = emailArr.length;
		$('emailUsrCnt').value = emailArr.length;
		var emailTable = "<table border=0 cellspacing=0 cellpadding=5>";
		emailTable += "<tr><td><strong>Recipients that are not currently NetGalley members:</strong></td></tr>";
		emailTable += "<tr><td><u>Email Addresses</u></td></tr>";

		for(i=0;i<emailArr.length;i++)
		{
			email =  trimString(emailArr[i]);
			if(email)
			{
				isEmptyTable = false;
				var fieldName = "EMAILUSER"+i;
				var emailCheck = "<input type=\"checkbox\" id=\""+fieldName+"\" name=\""+fieldName+"\" value=\""+email+"\" checked=\"checked\" onClick='removeEmailUser("+i+")'>";
				new Insertion.Bottom('MembersDetails', "<div style='margin-bottom:10px;'><span id='emailRow_"+i+"'><span style='font-size:10px;margin-right:15px;'><strong>Email: </strong></span><span style='font-size:10px;margin-top:5px;margin-bottom:5px;'>"+emailCheck+" "+email+"</span></span></div>");
				emailTable += "<tr id='emailUserRow"+i+"'><td>"+email+"</td></tr>";
			}
		}

		emailTable +="</table>";
		//if users are not selected.
		if(isEmptyTable)
		{
			emailTable = "";
		}
		$('nonNetGalleyUsers').innerHTML = emailTable;
		Element.hide('nonNetGalleyMembers');Element.show('MainBlock');
	}
}
*/

function nonNGMembers()//modified for #2426 on 6/12/2009,6/15/2009,6/16/2009
{
	
	if(!validateEmail())
	{
		return false;
	}
	else
	{
		var str= document.getElementById('csvFileData').value;
		var emailArr="";
		emailArr=str.split(";");//.getUnique();
		
		//window.alert("emailArr-->"+emailArr.length);
		
		var strOrg= document.getElementById('csvFileDataEmailName').value;
		var myArray="";
		myArray = strOrg.split(';');  
		var isEmptyTable = true;

		//window.alert("myArray-->"+myArray.length);
		if( myArray != "")
		{
				//clear all community members
				for(i=0; i<$('hid_emailCnt').value; i++)
				{
					var spanId = "emailRow_"+i;
					if( $(spanId) != null)
					$(spanId).remove();

					var spanIdname = "nameRow_"+i;
					if( $(spanIdname) != null)
					$(spanIdname).remove();
				}

				
				$('hid_emailCnt').value = myArray.length; // emailArr.length;
				$('emailUsrCnt').value = myArray.length; // emailArr.length;
				$('emailNameData').value=strOrg;
				var emailTable = "<table border=0 cellspacing=0 cellpadding=5>";
				emailTable += "<tr><td><strong>Recipients that are not currently NetGalley members:</strong></td></tr>";
				emailTable += "<tr><td><u>Email Addresses</u></td></tr>";

			
				for(i=0;i<myArray.length;i++)
				{
					
					var email= "";
					var name= "";
					
					if(myArray[i]!=null)//if(emailArr[i] != null  )
					{
							if(myArray[i].indexOf("@") > -1 )			
							{
								email =  trimString(myArray[i]);
								
							}
							if(myArray[i].indexOf("@")==-1  )//&& isNaN(myArray[i])
							{
								if(isNaN(myArray[i]))
									name =  myArray[i];
								else
									name= "Not Available";
								
							}
							
							isEmptyTable = false;		
							var fieldName = "EMAILUSER"+i;												 
							var emailCheck = "<input type=\"checkbox\" id=\""+fieldName+"\" name=\""+fieldName+"\" value=\""+email+"\" checked=\"checked\" onClick='removeEmailUser("+i+")'>";	
							var fieldUserName = "NAMEOFUSER"+i;							
							var nameCheck = "<input type=\"hidden\" id=\""+fieldUserName+"\" name=\""+fieldUserName+"\" value=\""+name+"\" size=\"15\" readonly >";		 
							
							if(email)
							{
									
							new Insertion.Bottom('MembersDetails', "<div style='margin-bottom:10px;' id='EmailDetails'"+i+" ><span id='emailRow_"+i+"'><span style='font-size:10px;margin-right:15px;'><strong>Email: </strong></span><span style='font-size:10px;margin-top:5px;margin-bottom:5px;'>"+emailCheck+" "+email+"</span></span></div>");		
							}
							else
							{
							new Insertion.Bottom("MembersDetails", "<div style='margin-bottom:10px;'><span id='nameRow_"+i+"'><span style='font-size:10px;margin-top:5px;margin-bottom:5px;'>"+nameCheck+"</span></span></div>");
							
							//new Insertion.Bottom("MembersDetails", "<div style='margin-bottom:10px;'><span id='nameRow_"+i+"'><span style='font-size:10px;margin-right:15px;'><strong>Name: </strong></span><span style='font-size:10px;margin-top:5px;margin-bottom:5px;'>"+i+"--"+nameCheck+"</span></span></div>");
							
							}
						emailTable += "<tr id='emailUserRow"+i+"'><td>"+email+"</td></tr>";  
					}//if(myArray[i]!=null)
				}//for
		}//if myarray
		else //if user enters emailids manually instead of importing CSV
		{
		
				//clear all community members
				for(i=0; i<$('hid_emailCnt').value; i++)
				{
					var spanId = "emailRow_"+i;
					if( $(spanId) != null)
					$(spanId).remove();
				}
				$('hid_emailCnt').value = emailArr.length;
				$('emailUsrCnt').value = emailArr.length;
				var emailTable = "<table border=0 cellspacing=0 cellpadding=5>";
				emailTable += "<tr><td><strong>Recipients that are not currently NetGalley members:</strong></td></tr>";
				emailTable += "<tr><td><u>Email Addresses</u></td></tr>";

				for(i=0;i<emailArr.length;i++)
				{
					email =  trimString(emailArr[i]);
					if(email)
					{
						isEmptyTable = false;
						var fieldName = "EMAILUSER"+i;						
						var emailCheck = "<input type=\"checkbox\" id=\""+fieldName+"\" name=\""+fieldName+"\" value=\""+email+"\" checked=\"checked\" onClick='removeEmailUser("+i+")'>";
						new Insertion.Bottom('MembersDetails', "<div style='margin-bottom:10px;'><span id='emailRow_"+i+"'><span style='font-size:10px;margin-right:15px;'><strong>Email: </strong></span><span style='font-size:10px;margin-top:5px;margin-bottom:5px;'>"+emailCheck+" "+email+"</span></span></div>");
						emailTable += "<tr id='emailUserRow"+i+"'><td>"+email+"</td></tr>";
					}
				}
		
		
		}//else
		emailTable +="</table>";
		//if users are not selected.
		if(isEmptyTable)
		{
			emailTable = "";
		}
		
		$('nonNetGalleyUsers').innerHTML = emailTable;
		Element.hide('nonNetGalleyMembers');Element.show('MainBlock');
	}
}

function removeEmailUser(id)
{
	if($("EMAILUSER"+id).checked == true)
	{
		setDisplayProperty($('emailUserRow'+id),'');
		$('emailUsrCnt').value = eval($('emailUsrCnt').value) + 1;
	}
	else
	{
		setDisplayProperty($('emailUserRow'+id),'none');
		$('emailUsrCnt').value = eval($('emailUsrCnt').value) - 1;
	}

	if(isEmailUserPreviewEmpty())
	{
		setDisplayProperty($('nonNetGalleyUsers'),'none');
	}
	else
	{
		setDisplayProperty($('nonNetGalleyUsers'),'');
	}
}

function isEmailUserPreviewEmpty()
{
	for(i=0; i<$('hid_emailCnt').value; i++)
	{
		var fieldName = "EMAILUSER"+i;
		if($(fieldName) != null)
		{
			if($(fieldName).checked)
			{
				return false;
			}
		}
	}
	return true;
}


function trimString (str) {
  str = this != window? this : str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
//************************************************************

//search NG members
function searchNGMembers()
{
    //trimming
    $("txtUserName").value = trim($("txtUserName").value);
    $("txtCompanyName").value = trim($("txtCompanyName").value);
    $("txtCity").value = trim($("txtCity").value);
    $("txtState").value = trim($("txtState").value);
    var galleyId = $("galleyID").value;
    if ($("txtUserName").value.length == 1)
    {
        alert('At least 2 letters are required for name search.');
        $("txtUserName").value = '';
        $("txtUserName").focus();
    }
    else if ($("txtCompanyName").value.length == 1)
    {
        alert('At least 2 letters are required for company name search.');
        $("txtCompanyName").value = '';
        $("txtCompanyName").focus();
    }
    else if ($("txtCity").value.length == 1)
    {
        alert('At least 2 letters are required for city search.');
        $("txtCity").value = '';
        $("txtCity").focus();
    }
    else if ($("txtState").value.length == 1)
    {
        alert('At least 2 letters are required for state search.');
        $("txtState").value = '';
        $("txtState").focus();
    }
    else if (($("txtUserName").value.length == 0) &&
        ($("txtCompanyName").value.length == 0) &&
        ($("txtCity").value.length == 0) &&
        ($("txtState").value.length == 0) &&
        ($("cmbGenre").value == 0) &&
        ($("cmbAssoc").value == 0))
    {
        alert('One or more of the fields must have search criteria for results to be displayed.');
        $("txtUserName").focus();
    }
    else
    {
        isSearched = true;
        var url = 'AJAXHandler.php';
        var pars = 'module=project&func=searchNGMembers&uname=' + $("txtUserName").value + '&cname=' + $("txtCompanyName").value + '&city=' + $("txtCity").value + '&state=' + $("txtState").value + '&genre=' + $("cmbGenre").value + '&assoc=' + $("cmbAssoc").value + '&galleyId=' + galleyId;

        var myAjax = new Ajax.Request(
                url,
                {
                    method: 'Post',
                    parameters: pars,
                    onComplete: searchNGMembersResponse,
                    onFailure: AJAXReportError
                });
    }
    return false;
}

function searchNGMembersResponse(originalRequest)
{
	text = originalRequest.responseText;
	text = text.replace(/^\s*/, '').replace(/\s*$/, '');
	$("divSearchResults").innerHTML = text;
    $("systemWorking").hide();
	$("nghiddSearchUserList").value=$("hiddSearchUserList").value; //Fix for #2484
}

function getSelectedUsers()
{
	var userList = "";
	var userArray = $("hiddSearchUserList").value.split(",");
	for(i=0; i<userArray.length; i++)
	{
		if(userArray[i] != "")
		{
			if($("chkSearchResult_"+userArray[i]).checked)
			{
				if(userList != "")
					userList = userList + "," + userArray[i];
				else
					userList = userArray[i];
			}
		}
	}
	return userList;
}

var isMembersAdded = false;
var isSearched = false;
function addNGMembers()
{
	var finalUserIDs = "";
	var selectedUsers = getSelectedUsers();

	if($("hiddFinalUserList").value != "")
	{
		finalUserIDs = $("hiddFinalUserList").value;
	}
	if(selectedUsers != "")
	{
		if(finalUserIDs != "")
			finalUserIDs = finalUserIDs + "," + selectedUsers;
		else
			finalUserIDs = selectedUsers;
	}

	if(finalUserIDs == "" && !isSearched)
	{
		alert("Please first search the users and then add.");
		return false;
	}
	//To check whether users have been selected.
	var searchIDArray = $("hiddSearchUserList").value.split(",");
	var isMemberSelected = false;
	for(i=0; i<searchIDArray.length; i++)
	{
		if(searchIDArray[i] != "")
		{
			if($("chkSearchResult_"+searchIDArray[i]).checked)
			{
				isMemberSelected = true;
				isMembersAdded = true;
				break;
			}
		}
	}
	if(!isMemberSelected)
	{
		alert("Please select at least one user to add.");
		return false;
	}

	var url = 'AJAXHandler.php';
	var pars = 'module=project&func=addNGMembers&uids='+finalUserIDs;

	var myAjax = new Ajax.Request(
		url,
		{
			method: 'Post',
			parameters: pars,
			onComplete: addNGMembersResponse,
			onFailure: AJAXReportError
		});
	return false;
}

function addNGMembersResponse(originalRequest)
{
	text = originalRequest.responseText;
	text = text.replace(/^\s*/, '').replace(/\s*$/, '');
	$("divFinalList").innerHTML = text;
	$("nghiddFinalUserList").value=$("hiddFinalUserList").value; //Fix for #2484
}

function removeNGMembers()
{
	var userList = $("hiddFinalUserList").value;
	$("hiddFinalUserListOld").value = $("hiddFinalUserList").value;
	var userArray = $("hiddFinalUserList").value.split(",");
	var isMemberSelected = false;
	if(!isMembersAdded)
	{
		alert("First add the users in Invitation List table to remove.");
		return false;
	}
	for(i=0; i<userArray.length; i++)
	{
		if(userArray[i] != "")
		{
			//fix for Ticket #2484 
			if($("chkMemberToRemove_"+userArray[i]) == null)
				return;
			
			if($("chkMemberToRemove_"+userArray[i]).checked)
			{
				$("tr_"+userArray[i]).remove();
				userList = getStringByRemoveItem($("hiddFinalUserList").value, userArray[i]);
				isMemberSelected = true;
			}
		}
	}
	if(!isMemberSelected)
	{
		alert("Please select at least one user to remove.");
		return false;
	}
	$("hiddFinalUserList").value = userList;
	$("nghiddFinalUserList").value = userList;//fix for Ticket #2484 
	return false;
}

//returns string by removeing item from comma delimited string
function getStringByRemoveItem(commaSeparatedString, itemToRemove)
{
	var itemArray = commaSeparatedString.split(",");
	for(i=0; i<itemArray.length; i++)
	{
		if(itemArray[i] == itemToRemove)
		{
			itemArray.splice(i, 1);
			break;
		}
	}
	return itemArray.join(",");
}

//To add NetGalley member users
function addNetGalleyUsers()
{
	var ngUserIDArrayOld = $('hiddFinalUserListOld').value.split(",");
	var ngUserIDArray = $('hiddFinalUserList').value.split(",");
	//To clear all NG members
	for(i=0; i<ngUserIDArrayOld.length; i++)
	{
			var spanId = "ngUserRow_"+ngUserIDArrayOld[i];
			if( $(spanId) != null)
			$(spanId).remove();
	}
	//To add updated NG members
	var isEmptyTable = true;
	var emailTable = "<table border=0 cellspacing=0 cellpadding=5>";
	emailTable += "<tr><td colspan=\"2\"><strong>Recipients that are other NetGalley members:</strong></td></tr>";
	emailTable += "<tr><td width='200'><u>Name</u></td><td><u>Company</u></td></tr>";

	for(i=0; i<ngUserIDArray.length; i++)
	{
		var id = ngUserIDArray[i];
		if(id != "")
		{
			if($("tr_"+id) != null)
			{
				if($("tr_"+id).style.display != 'none')
				{
					var uid = "hiddNGUser"+id;
					var fieldName = "chkNGMember_"+id;
					var userEmail = $("chkMemberToRemove_"+id).value;
					var userCompany = $("hiddNGUserCompany_"+id).value;
					var label = $("hiddNGUserName_"+id).value;
					var alreadyFormValues = Form.serialize('sendReviewReq');
					isEmptyTable = false;

					//Add NG Member			
					
					var formField = "<input type=\"hidden\" id=\""+uid+"\" name=\""+uid+"\" value=\""+id+"\" ><input type=\"checkbox\" id=\""+fieldName+"\" name=\""+fieldName+"\" value=\""+userEmail+"\" checked onClick=\"removeNGUser("+id+");\">";

					new Insertion.Bottom('MembersDetails', "<div style='margin-bottom:10px;'><span id='ngUserRow_"+id+"'><span style='font-size:10px;margin-right:15px;'><strong>User: </strong></span><span style='font-size:10px;margin-top:5px;margin-bottom:5px;padding-left:5px;'>"+formField+" "+label+"</span></span></div>");
					emailTable += "<tr id='emailNGUserRow"+id+"'><td>"+label+"</td><td>"+userCompany+"</td></tr>";

				}
				else
				{
					//remove from main list
					var spanId = "ngUserRow_"+id;
					if($(spanId) != null)
					$(spanId).remove();
					// remove from search result
					var trId = "tr_"+id;
					if($(trId) != null)
					$(trId).remove();
					//update final list
					$('hiddFinalUserList').value = getStringByRemoveItem($('hiddFinalUserList').value, id);
				}
			}
		}
	}
	emailTable +="</table>";
	//if members are not selected.
	if(isEmptyTable)
	{
		emailTable = "";
	}

	$('divNetGalleyMembers').innerHTML = emailTable;
	Element.hide('searchNetGalley');Element.show('MainBlock');
}

function removeNGUser(id)
{
	if($("chkNGMember_"+id)== null)
		return;
	if($("chkNGMember_"+id).checked == true)
	{
	setDisplayProperty('emailNGUserRow'+id, '');
	setDisplayProperty("tr_"+id, '');
	}
	else
	{
	setDisplayProperty('emailNGUserRow'+id, 'none');
	setDisplayProperty("tr_"+id, 'none');
	}

	if(isNGUserPreviewEmpty())
	{
		setDisplayProperty($('divNetGalleyMembers'),'none');
	}
	else
	{
		setDisplayProperty($('divNetGalleyMembers'),'');
	}
}

function isNGUserPreviewEmpty()
{
	var ngUserIDArray = $('hiddFinalUserList').value.split(",");
	for(i=0; i<ngUserIDArray.length; i++)
	{
		var fieldName = "chkNGMember_"+ngUserIDArray[i];
		if($(fieldName) != null)
		{
			if($(fieldName).checked)
			{
				return false;
			}
		}
	}
	return true;
}

function setDisplayProperty(id, value)
{
	if($(id) != null)
	{
		$(id).style.display = value;
	}
}

function openImgWin(url,winName,param)
{
	newwindow=window.open(url,winName,param);
	if (window.focus) {newwindow.focus()}

}
///////////
function archiveGalleyRequest(reqid)
{
	if(confirm("Are you sure to archive this title request?"))
	{
		var pars = Form.serialize('frmReviewRequest');
		var url = "AJAXHandler.php?module=project&func=makeRequestArchive&reqid="+reqid;
		var myAjax = new Ajax.Request(
		url,
		{
			method: 'POST',
			parameters: pars,
			onComplete: reviewerResponse
		});
	}
}

function openEmailWin(url)
{
	var param = 'width=550,scrollbars=no,height=590,top=200,left=400,resizable=0';
	newwindow=window.open(url,'request',param);
	if (window.focus) {newwindow.focus()}
}
/*function openProfileWin(url)
{
	var param = 'width=595,scrollbars=no,height=650,top=200,left=400,resizable=0';
	newwindow=window.open(url,'profile',param);
	if (window.focus) {newwindow.focus()}
}*/

function openProfileWin(url) // Modifiied for #1967 on 6/12/2009
{
	  var myWidth = 0, myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	  }
	
	//window.alert( 'p-Height = ' + myHeight );
	if(myHeight > 580)
		window.open(url,'profile','height=650,width=610,scrollbars=yes,left=225');
     else
		window.open(url,'profile','height=650,width=610,scrollbars=no,left=225');
}

function goToMymedia()
{
    self.close();
    opener.location = "index.php?module=media&func=mediaList&navLink=";
}

msg = "Once you edit the default email it will be sent for all subsequent\napproved or declined requests. If you'd like to edit an email\n in the future, your previous edits will display.";

//function added to check which reading option is checked.
function chkReadOption(url,chkval)
{
	if(chkval == "0")
		var new_url=url+"&rf="+document.getElementById('chksonyreader').checked;
	if(chkval == "1")
		var new_url=url+"&rf="+document.getElementById('chkkindle').checked;
	if(chkval == "2")
		var new_url=url+"&rf="+document.getElementById('chkother').checked;
	/*if(chkval == "3")
		var new_url=url+"&rf="+document.getElementById('chkprotectedpdf').checked;*/
	
	window.open(new_url,'popuppage','width=370,scrollbars=yes,height=155,top=400,left=400');	
}
//function added to redirect user to profile management page to add kindle address
function goToMyProfile()
{
        self.close();
		//window.open("index.php?module=ProfileMgmt&func=displayProfile&navSub=navSub_Profile&navLink=navLink_ContactInfo","profile");
        //window.location = "index.php?module=ProfileMgmt&func=displayProfile&navSub=navSub_Profile&navLink=navLink_ContactInfo";
        opener.location = "index.php?module=ProfileMgmt&func=displayProfile&navSub=navSub_Profile&navLink=navLink_ContactInfo";
}

//basename Returns filename component of path
function basename(path, suffix) {
  
    var b = path.replace(/^.*[\/\\]/g, ''); //  http://kevin.vanzonneveld.net
    
    if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {
        b = b.substr(0, b.length-suffix.length);
    }
    
    return b;
}

//function to redirect to user's print request setup page. fix for #2346 on 7/22/2009 >>Revisions made with reference to 717_reading_options.jpg
function gotoMyPrintRequestSetup()
{
        self.close();
		//opener.window.close();
		window.open("index.php?module=project&func=printGalleyList&navSub=navSub_MyGalley&navLink=navLink_PrintGalley","Print Request Setup");
        //window.location = "index.php?module=project&func=printGalleyList&navSub=navSub_MyGalley&navLink=navLink_PrintGalley";
        //opener.location = "index.php?module=project&func=printGalleyList&navSub=navSub_MyGalley&navLink=navLink_PrintGalley";		
}
//Fix for #2483 : checkAll and uncheckAll functions added
function checkAll(field)
{
	
	if(field == null)
		return;
	if(field.toString().indexOf("Array") == -1){
			field.checked = true;
	}
	if(field.length > 0 )
	{	
	for (i = 0; i < field.length; i++)
		field[i].checked = true ;
	}
}//function
function uncheckAll(field)
{
	if(field == null)
		return;
	
	if(field.toString().indexOf("Array") == -1){
		if(!field.disabled)
			field.checked = false;
	}
	if(field.length > 0 )
	{	
		for (i = 0; i < field.length; i++)
		{
		if(!field[i].disabled)
			field[i].checked = false ;
		}
	}//if
}//function
//fix for Ticket #2484: 714_send_invite1.jpg
function CheckAll_Add(userlist)
{
	var userArray = userlist.split(",");
	if(document.getElementById('Check_ctr').checked==true){	
		for(i=0; i<userArray.length; i++)
		{
			if(userArray[i] != "")
			{
				$("chkSearchResult_"+userArray[i]).checked=true;
			}
		}//for
	}else{
		for(i=0; i<userArray.length; i++)
		{
			if(userArray[i] != "")
			{
				$("chkSearchResult_"+userArray[i]).checked=false;
			}
		}//for
	}//else
}//function

function CheckAll_Remove(userlist)
{
	var userArray = userlist.split(",");
	if(document.getElementById('Check_ctr_remove').checked==true){	
		for(i=0; i<userArray.length; i++)
		{
			if($("chkMemberToRemove_"+userArray[i]) == null)
				return;
			
			if(userArray[i] != "")
			{
				$("chkMemberToRemove_"+userArray[i]).checked=true;
			}
		}//for
	}else{
		for(i=0; i<userArray.length; i++)
		{
			if($("chkMemberToRemove_"+userArray[i]) == null)
				return;
			
			if(userArray[i] != "")
			{
				$("chkMemberToRemove_"+userArray[i]).checked=false;
			}
		}//for
	}//else
}//function
//fix for #2492 >> Popup for Print request Setup page redirect removed.
function goToPrintRequestSetup()
{
        self.close();
		//index.php?module=project&func=printGalleyList&navSub=navSub_MyGalley&navLink=navLink_PrintGalley
        window.location = "index.php?module=project&func=printGalleyList";
        opener.location = "index.php?module=project&func=printGalleyList";
}
//js function to show the processing window and call a serverside function
 function showProcessing()
    {
        var fullyQualifiedFilenameOfBookToPackage = document.getElementById('fullyQualifiedFilename').value;
        url = "AJAXHandler.php?module=project&func=getPackagingServlet&fullyQualifiedFilenameOfBookToPackage="+fullyQualifiedFilenameOfBookToPackage;
        //var pars = "title=Edit Galley - Upload PDF for SONY Reader";
		var myAjax = new Ajax.Request(
		url,
		{
			method: 'Post',
            onFailure: AJAXReportError,
			//parameters: pars,
			onComplete: showResult
		});
    }
  // after completing the processing this function takes care.
  function showResult(originalRequest)
    {
    var res = originalRequest.responseText;
	res = res.replace(/^\s*/, '').replace(/\s*$/, '');
    alert(res);
    self.close();
    opener.location.reload(true);
    }

