﻿// JScript File
/*########################################################  additional jquery  / global   ############################*/
Fake = function()
{
return true;
} 
findCSS = function(myid) {
    var objStyle = document.getElementById(myid);
    if (objStyle == null) {
        return false;
    }
    return true;
};
LoadCSS = function(url, myid) {
    try {
        if (!findCSS(myid)) {
            var cssNode = document.createElement('link');
            cssNode.id = myid;
            cssNode.href = url;
            cssNode.type = 'text/css';
            cssNode.rel = 'stylesheet';
            cssNode.media = 'screen';
            var headID = document.getElementsByTagName("head")[0];
            headID.appendChild(cssNode);
            var done = false;
            cssNode.onload = cssNode.onreadystatechange = function() {
            if (!done && (!this.readyState ||
                  this.readyState == "loaded" || this.readyState == "complete")) {
                done = true;
                Fake();
                cssNode.onload = cssNode.onreadystatechange = null;
            }
            };
            return true;
        }
    }
    catch (Error) {
        return false;
    }
    return true;
};
changeCSS = function(whichSheet, parentpath) {
    var expDate = new Date("October 12, 2100");
    skincookie = getCookie("elssskin");
    setCookie("elssskin", whichSheet, expDate, "/", "", "");
    try {
        if (!findCSS(whichSheet)) {
           getCSS(parentpath + whichSheet, null, whichSheet);
        }
        else {
            var elms = document.getElementsByClassName("altcss");
            var c = document.elms.length;
            for (var i = 0; i < c; i++) {
                //   c[i].disabled = true
                var objCope = c[i];
                c[i].parentNode.removeChild(c[i]);
            }
        }
    }
    catch (Error) {

    }
};
getCSS = function(url, media, myid) {
var cssNode = document.createElement('link');
var attr = document.createAttribute("class");
attr.value = "altcss";
cssNode.attributes.setNamedItem(attr);
    cssNode.isAlternate = false;
    cssNode.isPrefAlternate = false;
    cssNode.id = myid;
    cssNode.title = url;
    cssNode.href = url,
    cssNode.media = media || 'screen';
    cssNode.type = 'text/css';
    cssNode.rel = 'stylesheet';
    var headID = document.getElementsByTagName("head")[0];
    headID.appendChild(cssNode);
};
function LoadJS(libraryName,id) {
    try {
        document.write('<script type="text/javascript" src="' + libraryName + '" id="' + id + '"><\/script>');
        return document.getElementById(id); 
    }
    catch (e) {
        var script = document.createElement('script');
        script.type = 'text/javascript'; script.src = libraryName;script.id = id;
        document.getElementsByTagName('head')[0].appendChild(script);
        return script;
    }
    
}

getScript = function(url, callback, id) {
    if (document.getElementById(id) == null) {
        var head = document.getElementsByTagName("head")[0];
        var script = document.createElement("script");
        script.src = url;
        script.id = id;
        head.appendChild(script);
        // Handle Script loading 
        {
            var done = false;

            // Attach handlers for all browsers 
            script.onload = script.onreadystatechange = function() {
                if (!done && (!this.readyState ||
                  this.readyState == "loaded" || this.readyState == "complete")) {
                    done = true;
                    if (callback) {
                        if (id == 'jquery')
                        { jQuery.noConflict(); }

                        callback();
                    }

                    // Handle memory leak in IE 
                    script.onload = script.onreadystatechange = null;
                }
            };
        }
    }
    else {
        done = true;
        if (callback) {
            if (id == 'jquery')
            { jQuery.noConflict(); }  
            callback();
        }
    }

    // We handle everything using the script element injection 
    return undefined;
}; 

/*########################################################  Eguipment   ############################*/
function ToggleEquipment(updateButtonId,equipmentId){
	var editBox = {		
		UpdateButtonId:updateButtonId,
		ErrorBoxId:'pageError'
	}
	if(equipmentId && equipmentId!=0){			            
    	EquipmentService.ToggleEquipment(equipmentId,OnSucceeded, OnError, editBox);
	}
}
/*########################################################  Companies   ############################*/
function ToggleCompany(updateButtonId,companyId){
	var editBox = {		
		UpdateButtonId:updateButtonId,
		ErrorBoxId:'pageError'
	}
	if(companyId && companyId!=0){			            
    	CompanyService.ToggleCompany(companyId,OnSucceeded, OnError, editBox);
	}
}
/*########################################################  Custom Fields for Equipment   ############################*/
function DCustomField(item,container){
	$('dName').update(item.name);
	$('dId').value=item.id;
	$('deleteCustomFieldErrorContainer').hide();	
	container.show();
	$('deleteCustomFieldButton').focus();
}

function DeleteCustomField(updateButtonId,container)
{   	
	var itemId;
  itemId = $('dId').value;
	if(itemId && itemId!=0){	
		var editBox = {
			Container:container,
			UpdateButtonId:updateButtonId,
			ErrorBoxId:'deleteCustomFieldError'
		}			            
		EquipmentService.DeleteCustomField(itemId,OnSucceeded, OnError, editBox);
	}
}
function ECustomField(item,container){
	$('eName').value=item.name;	
	$('eId').value=item.id;	
	container.show();
}
function UCustomField(updateButtonId,container){
	var name, id, categoryId;
	name=$('eName').value;	
	categoryId=$('eCategoryId').value;
	if($('eId').value==''){
		id=0;		
	}else{
		id=$('eId').value;		
	}
	var editBox = {
		Container:container,
		UpdateButtonId:updateButtonId,
		ErrorBoxId:'editCustomFieldError'
	}
	EquipmentService.UpdateCustomField(id,categoryId,name,OnSucceeded, OnError, editBox);
}
/**############################################# Managers ############################################*/
function AddComment(){
	var editBox={		
		ErrorBoxId:'showCommentsError',
		LoadingImg:'commentsLoading'
	}
	var cId = $('cManagerId').value;
	var cName = $('addCommentName').value;
	var cBody = $('addCommentBody').value;
	if((!cName || cName=='')||(!cBody ||cBody=='')){
		$(editBox.ErrorBoxId).update("Please fill required fields.");
		$(editBox.ErrorBoxId+'Container').show();		
	}else{
		$('cContent').update('');
		$('commentsLoading').show();
		SalesManagerService.AddComment(cId,cName,cBody,LoadCommentsOnSucceeded, OnError, editBox);		
	}
}
function ShowComments(managerId,managerName, container){	
	$('cContent').update('');
	$('cManagerName').update(managerName);
	//clear fields
	$('cManagerId').value=managerId;
	$('addCommentName').value='';
	$('addCommentBody').value='';
	
	$('commentsLoading').show();
	container.show();
	var editBox={		
		ErrorBoxId:'showCommentsError',
		LoadingImg:'commentsLoading'
	}
	SalesManagerService.LoadComments(managerId,LoadCommentsOnSucceeded, OnError, editBox);	
}
function LoadCommentsOnSucceeded(result, editBox){
	$('commentsLoading').hide();
	$('cContent').update(result);
	//clear fields	
	$('addCommentName').value='';
	$('addCommentBody').value='';
}
function ToggleManager(updateButtonId,managerId){
	var editBox = {		
		UpdateButtonId:updateButtonId,
		ErrorBoxId:'pageError'
	}
	if(managerId && managerId!=0){			            
    	SalesManagerService.ToggleManager(managerId,OnSucceeded, OnError, editBox);
	}
}
/**############################################# Regions ############################################*/
function URegion(region,container,countryDropDownListId){
	$('eName').value=region.Name;	
	$('eId').value=region.Id;	
	if(region.CountryId && region.CountryId!=0){
		$(countryDropDownListId).value=region.CountryId;
	}
	$('eStatesIds').value=region.States;
	$('editRegionErrorContainer').hide();
	UpdateCountryField(countryDropDownListId);	
	container.show();
}

function UpdateRegion(updateButtonId,container){
var regionWrapper = {
		Id:$('eId').value,
		Name:$('eName').value,
		States:$('eStatesIds').value,
		CountryId:$('eCountryId').value
	}
	var editBox = {
		Container:container,
		UpdateButtonId:updateButtonId,
		ErrorBoxId:'editRegionError'
	}
	SalesManagerService.UpdateRegion(Sys.Serialization.JavaScriptSerializer.serialize(regionWrapper),
							OnSucceeded, OnError, editBox);
}
function DRegion(region,container){
	$('dName').update(region.Name);	
	$('dId').value=region.Id;	
	$('deleteRegionError').hide();
	container.show();
}
function DeleteRegion(updateButtonId,container){
	var id=$('dId').value;
	var editBox = {
		Container:container,
		UpdateButtonId:updateButtonId,
		ErrorBoxId:'deleteRegionError'
	}	
	SalesManagerService.DeleteRegion(id,OnSucceeded, OnError, editBox);
}
function UpdateAssignedStatesList(regionDropDown,stateIds){
	var editBox = {				
		ErrorBoxId:'pageError',
		SelectedStatesBox:stateIds
	}	
	if($(regionDropDown).value && !$(regionDropDown).value.blank()){
		SalesManagerService.GetRegionStates($(regionDropDown).value,OnGetStatesSucceeded,OnError,editBox);
	}else{
		$('eStatesContainer').update("&nbsp;");
	}
}

function UpdateCountryField(countryDropDownListId){
	$('eCountryId').value=$(countryDropDownListId).value;
	var editBox = {				
		ErrorBoxId:'editRegionError',
		SelectedStatesBox:'eStatesIds'
	}	
	if($('eId').value && !$('eId').value.blank() && $('eCountryId').value && !$('eCountryId').value.blank()){
		SalesManagerService.GetStates($('eId').value,$('eCountryId').value,OnGetStatesSucceeded,OnError,editBox)
	}
}

function OnGetStatesSucceeded(result, editBox){
	$('eStatesContainer').update(result.Message);
	var cbg = new CheckBoxGroup($('eStatesContainer'));
	cbg.set_CheckedListTextBoxID(editBox.SelectedStatesBox);
	cbg.initialize();
}
/**############################################# CHeckBoxGroup ############################################*/
CheckBoxGroup = function(element) {    
    this._element = $(element);
    this._checkedListTextBoxID = "";
    this._checkedListTextBox;
		this._checkBoxes = new Array();	
		this._debugConsoleID='debugConsole';
}

CheckBoxGroup.prototype = {
    initialize : function() {        
        this._checkedListTextBox=$(this._checkedListTextBoxID);
				this._checkBoxes=$A(this._element.getElementsByTagName("input"));
				this._checkBoxes=this._checkBoxes.findAll(function(inputElement) { return inputElement.type.toLowerCase()=="checkbox"});
        this.debug("Total Number Of Checkboxes Found:"+this._checkBoxes.length);
        for(var i = 0; i<this._checkBoxes.length; i++){		
					Event.observe(this._checkBoxes[i], 'click', this.updateChecked.bindAsEventListener(this)); 
        }
        this.updateBoxes();
    },
		updateChecked : function(){				
			this._checkedListTextBox.value="";
			for(var i = 0; i<this._checkBoxes.length; i++){
				if(this._checkBoxes[i].checked){
					//this._checkedListTextBox.value+=this._checkBoxes[i].id+"="+this._checkBoxes[i].value+",";
					this._checkedListTextBox.value+=this._checkBoxes[i].value+",";
				}			
			}
			this.debug("updateChecked.value:"+this._checkedListTextBox.value);
	},
	updateBoxes : function(){
		var values = this._checkedListTextBox.value.split(',');		
		var value;
		//clean values
		for(var j =0; j<this._checkBoxes.length; j++){				
					this._checkBoxes[j].checked=false;				
		}
		//set checked
		for(var i = 0; i<values.length; i++){			
			value=values[i];
			for(var j =0; j<this._checkBoxes.length; j++){
				if(this._checkBoxes[j].value==value){
					this._checkBoxes[j].checked=true;
				}
			}						
		}		
		this.debug("updateChecked.value:"+this._checkedListTextBox.value);
		this.updateChecked();
	},
    dispose : function() {
        // TODO: add your cleanup code here
        CheckBoxGroup.callBaseMethod(this, 'dispose');
    },
    //-----------------
    get_CheckedListTextBoxID : function() {
        return this._checkedListTextBoxID;
    },
    set_CheckedListTextBoxID : function(value) {
        this._checkedListTextBoxID = value;
    },
    debug : function Debug(info) {
		if(this._debugConsoleID && $(this._debugConsoleID)){
			$(this._debugConsoleID).value+=info+"\n";
		}
	}
}



/**############################################# end CHeckBoxGroup ############################################*/

/**
 * the callback function that processes the Web Service return value and hides the box.
 * also makes a postback to update the list
 * @param {Object} result server output
 * @param {Object} editBox a json object contains modal container and UpdateButton
 */
function OnSucceeded(result, editBox)
{			
	if(editBox.Container){	editBox.Container.hide();	}
	if(editBox.LoadingImg){$(editBox.LoadingImg).hide();}
	if(editBox.UpdateButtonId){__doPostBack($(editBox.UpdateButtonId).id,'');}
}

/**
 * Shows error row and populates it with server output
 * @param {Object} result
 */
function OnError(result, editBox)
{		
	$(editBox.ErrorBoxId).update(result._message);
	$(editBox.ErrorBoxId+'Container').show();					
	if(editBox.LoadingImg){$(editBox.LoadingImg).hide();}
}


//images upload 
/* ******************************************
 *	FileProgress Object
 *	Control object for displaying file info
 * ****************************************** */

function FileProgress(fileObj, target_id) {
	this.file_progress_id = "divFileProgress";

	this.fileProgressWrapper = document.getElementById(this.file_progress_id);
	if (!this.fileProgressWrapper) {
		this.fileProgressWrapper = document.createElement("div");
		this.fileProgressWrapper.className = "progressWrapper";
		this.fileProgressWrapper.id = this.file_progress_id;

		this.fileProgressElement = document.createElement("div");
		this.fileProgressElement.className = "progressContainer";

		var progressCancel = document.createElement("a");
		progressCancel.className = "progressCancel";
		progressCancel.href = "#";
		progressCancel.style.visibility = "hidden";
		progressCancel.appendChild(document.createTextNode(" "));

		var progressText = document.createElement("div");
		progressText.className = "progressName";
		progressText.appendChild(document.createTextNode(fileObj.name));

		var progressBar = document.createElement("div");
		progressBar.className = "progressBarInProgress";

		var progressStatus = document.createElement("div");
		progressStatus.className = "progressBarStatus";
		progressStatus.innerHTML = "&nbsp;";

		this.fileProgressElement.appendChild(progressCancel);
		this.fileProgressElement.appendChild(progressText);
		this.fileProgressElement.appendChild(progressStatus);
		this.fileProgressElement.appendChild(progressBar);

		this.fileProgressWrapper.appendChild(this.fileProgressElement);

		document.getElementById(target_id).appendChild(this.fileProgressWrapper);
		FadeIn(this.fileProgressWrapper, 0);

	} else {
		this.fileProgressElement = this.fileProgressWrapper.firstChild;
		this.fileProgressElement.childNodes[1].firstChild.nodeValue = fileObj.name;
	}

	this.height = this.fileProgressWrapper.offsetHeight;

}
FileProgress.prototype.SetProgress = function(percentage) {
	this.fileProgressElement.className = "progressContainer green";
	this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[3].style.width = percentage + "%";
}
FileProgress.prototype.SetComplete = function() {
	this.fileProgressElement.className = "progressContainer blue";
	this.fileProgressElement.childNodes[3].className = "progressBarComplete";
	this.fileProgressElement.childNodes[3].style.width = "";

}
FileProgress.prototype.SetError = function() {
	this.fileProgressElement.className = "progressContainer red";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

}
FileProgress.prototype.SetCancelled = function() {
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

}
FileProgress.prototype.SetStatus = function(status) {
	this.fileProgressElement.childNodes[2].innerHTML = status;
}

FileProgress.prototype.ToggleCancel = function(show, upload_obj) {
	this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
	if (upload_obj) {
		var file_id = this.file_progress_id;
		this.fileProgressElement.childNodes[0].onclick = function() { upload_obj.cancelUpload(file_id); return false; };
	}
}

function uploadError(file, errorCode, message) {
	var UploadError = $('UploadError');
	$('divFileProgressContainer').hide();
	try {
		UploadError.show();
		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			UploadError.update("Upload Error: " + message);			
			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			UploadError.update("Upload Failed.");
			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			UploadError.update("Server (IO) Error");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			UploadError.update("Security Error");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			UploadError.update("Upload limit exceeded.");
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
			UploadError.update("Failed Validation.  Upload skipped.");
			this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:			
			if (this.getStats().files_queued === 0) {
				$('divFileProgressContainer').hide();
			}			
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			$('divFileProgressContainer').hide();
			break;
		default:
			$('divFileProgressContainer').hide();
			UploadError.update("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);			
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

function uploadProgress(fileObj, bytesLoaded) {

	try {
		var percent = Math.ceil((bytesLoaded / fileObj.size) * 100);
		var progress = new FileProgress(fileObj,  this.getSetting("upload_target"));
		progress.SetProgress(percent);
		if (percent === 100) {
			progress.SetStatus("Creating thumbnail...");
			progress.ToggleCancel(false, this);
		} else {
			progress.SetStatus("Uploading...");
			progress.ToggleCancel(true, this);
		}
	} catch (ex) { 
	//this.debugMessage(ex); 
	}
}