var initialFieldToFocus = "";
var controlsToDisable = new Array();
var controlsToHide = new Array();
var checkedBoxes = new Array();
var isSysAdmin = false;
var printableQuoteMargin = "";
var showSupplierDetailsOnPrintableQuote = true;
var dataHasChanged = false; //boolean, if no data has been changed, no need to notify the user
var timer;
var canProceedToAct = true;
var numRowsSelected = 0;
var contextmenuIsShowing = false;
var rowCounter = 0;
var roleCheckboxSelector = '#roleContainer input:checkbox';
	
	function GetRadWindow()
	{
		var oWindow = null;
		if (window.radWindow) oWindow = window.radWindow; //Will work in Moz in all cases, including clasic dialog
		else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;//IE (and Moz az well)
		return oWindow;
	}
	
	function CloseSelf() {
		var window = GetRadWindow();
		if (window != null) {
			window.close();
		}
	}

	function CloseWindowOnTimeout() {
		var window = GetRadWindow();
		if (window != null) {
			window.close();
			self.location.reload(true);
		}
	}

	function CloseActiveToolTip() {
		var tooltip = Telerik.Web.UI.RadToolTip.getCurrent();
		if (tooltip) tooltip.hide();
    }  


    function MailTo(anchor, mailToLink) {
        jQuery(anchor).attr("href", mailToLink);
        jQuery(anchor).click();
        
    }


function ProcessLogin(isSecure, urlPost)
{
	var postURL = urlPost;
	if (isSecure == 'Y')
	{
		document.forms[0].action = postURL.replace(/http:/i,'https:');
	}
	else
	{
		document.forms[0].action = postURL;
	}
	document.forms[0].submit();
}







function toggleCheckAll(control, baseName, itemName) {
	var checked = control.checked;
	
}


function runPrint() {
	hideControls();
	print();
	showHiddenControls();
}




///function to disable a button after it has been clicked
function disableOnClick(control, isSubmit) {    
	if(isSubmit) {
		document.forms[0].submit();
	} else {
		control.click();
	}
	control.disabled = true;
	return true;
}


function addControlToHide(controlId) {
	control = $("#" + controlId);
	if (control) {
		controlsToHide[controlsToHide.length] = control;
	}
}

function showHiddenControls() {
	for (var x = 0; x < controlsToHide.length; x++) {
		controlsToHide[x].style.display = "block";
	}
}


function hideControls() {
	for (var x = 0; x < controlsToHide.length; x++) {
		controlsToHide[x].style.display = "none";
	}
}



function addControlToDisableArray(controlId) {
	control = $("#" + controlId);
	if(control) {
		controlsToDisable[controlsToDisable.length] = control;
	}
}

function disableControlsOnClick(control, isSubmit) {
    alert('here');
    if(isSubmit) {
		document.forms[0].submit();
	} else {
		control.click();
	}
	
	for(var x = 0; x < controlsToDisable.length; x++) {
		controlsToDisable[x].disabled = true;
	}
	return true;
}


function popupCentreWindow(windowManagerId, winURL, winX, winY) {
	var oWmgr = $find(windowManagerId);
	//alert(windowManagerId);
	//alert(oWmgr);
	var winW = winX;
	var winH = winY;

	if (parseInt(navigator.appVersion) > 3) {
		if (navigator.appName == "Netscape") {
			winW = window.innerWidth - 40;
			winH = window.innerHeight - 40;
		}
		if (navigator.appName.indexOf("Microsoft") != -1) {
			winW = document.body.offsetWidth - 40;
			winH = document.body.offsetHeight - 40;
		}
	}
	
	if (winX > winW) 
	{
		winX = winW;
	}
	if (winY > winH) 
	{
		winY = winH;
	}
	
	if (oWmgr != null) {
		var oWnd = oWmgr.open(unescape(winURL));
		oWnd.hide();
		oWnd.set_modal(true);
		oWnd.setSize(winX, winY);
		oWnd.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Resize);
		oWnd.center();
		oWnd.show();
	}

	return oWnd;

}

function popupCentreWindowWithPosition(windowManagerId, winURL, winX, winY, xpos, ypos) {

	var oWmgr = $find(windowManagerId);
	//alert(windowManagerId);    
	if (oWmgr != null) {
		var oWnd = oWmgr.open(unescape(winURL));
		oWnd.hide();
		//oWnd.set_modal(true);
		oWnd.setSize(winX, winY);
		oWnd.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Maximize + Telerik.Web.UI.WindowBehaviors.Minimize + Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Resize);
		oWnd.center();
		var bounds = oWnd.getWindowBounds();
		oWnd.MoveTo(bounds.x + xpos, bounds.y + ypos);
		oWnd.show();
	}

	return oWnd;
}

function generatePrintablePopupWithMargin(windowManagerId, baseUrl, width, height) {
	if (printableQuoteMargin != "") {
		baseUrl = baseUrl + "&margin=" + printableQuoteMargin;
	}
	baseUrl += "&ssdet=" + showSupplierDetailsOnPrintableQuote;
	//alert(baseUrl);
	//popupCentreWindow(windowManagerId, baseUrl, 775, 575);
	var winn = popupCentreWindow(windowManagerId, baseUrl, width, height);
	
	return false;
}







function handleEnterKey(btnId){
	
	var btnToClick = document.getElementById(btnId);
	if(btnToClick.click) {
		btnToClick.click();
		return false;
	}
}


function AutoWireUpEnterKeyButtonClickEvent(inputFieldToTrack, buttonToClickId) {
	$('#' + inputFieldToTrack).bind('keydown', { buttonIdToClick: '#' + buttonToClickId }, handleEnterKeyButtonClick);
}




function handleEnterKeyButtonClick(e) {
	if (e.which == 13) {
		var buttonName = e.data.buttonIdToClick;
		if ($(buttonName).length) {
			$(buttonName).click();
		}
		return true;
	}
	return true;
}



function submitOnEnter()
{
   if (this.window.event.keyCode == 13)
		  this.document.submit();
	this.document.submit();
}


function removeTextFromTextBox(field)
{
	if(field.length && field.value) {
		field.value = "";
	}

}



function setPrintableQuoteMargin(marginValue) {
	printableQuoteMargin = marginValue;
}


function setShowSupplierDetailsOnPrint(showOrNo) {
	showSupplierDetailsOnPrintableQuote = showOrNo;
}
	

/*
Note that these two methods are here but have NO implementation.  Each page which uses
the date picker or time picker should implement these javascript methods if they need to.
*/
function OnTimePickerOpening(sender, eventArgs) {
}

function OnDatePickerOpening(sender, eventArgs) {
}


	


function dataWasEntered()
{
	dataHasChanged = true; 
	return false;
}


function confirmPushCompanyNameChange(hiddenFieldName) {
	return true;
}


function canProceed() {
	if (canProceedToAct) {
		canProceedToAct = false;
		return true;
	} else {
	    return canProceedToAct;
	}
}

function resetCanProceed() {
	canProceedToAct = true;
}

function SelectRow(row, even, leftClick, checkBox) {
	if (contextmenuIsShowing) return;   
	   
	var _row = document.getElementById(row);        
	var _checkBox = document.getElementById(checkBox);


	if (_row.className == "darkGray" && leftClick == "true") {
		if (even == "true") {
			_row.className = "even";
		}
		else {
			_row.className = "";
		}
		_checkBox.checked = false;
		numRowsSelected--;
	}
	else if (_row.className != "darkGray" && leftClick== "true") {
		_row.className = "darkGray";
		_checkBox.checked = true;
		numRowsSelected++;
	}

	DisplayCorrectBottomLinks();        
}

function DisplayCorrectBottomLinks() {
	var _enabledLinks = document.getElementById('enabledLinks');
	var _disabledLinks = document.getElementById('disabledLinks');
		
	if (numRowsSelected > 0) {
		_enabledLinks.style.display = 'inline'
		_disabledLinks.style.display = 'none'
	}
	else {
		_enabledLinks.style.display = 'none'
		_disabledLinks.style.display = 'inline'
	}
}

function ShowContextMenu(contextMenuName, evt, nameOfRepeater, nameOfRow, idOfRowClicked) {
	contextmenuIsShowing = true;
	var e = (window.event) ? window.event : evt;       
		
	var xPos = e.clientX;       
	var yPos = e.clientY;        

	//this little bit determines if the user has scrolled down or right so that I can popup the context menu in the right place
	var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;        
	var dsocleft = document.all ? iebody.scrollLeft : pageXOffset;
	var dsoctop = document.all ? iebody.scrollTop : pageYOffset;

	var cntxtMn = document.getElementById(contextMenuName);

	cntxtMn.style.display = 'block';
	if (yPos < iebody.clientHeight / 2) {
			
		cntxtMn.style.top = yPos + dsoctop - 20 + "px";
		cntxtMn.style.left = xPos + dsocleft - 20 + "px";
	}
	else {
					
		cntxtMn.style.top = yPos + dsoctop - cntxtMn.offsetHeight + 20 + "px";
		cntxtMn.style.left = xPos + dsocleft - 20 + "px";
	}

	//deselect any selected rows
	SelectDeselectAllRows_helperMethod(nameOfRepeater, nameOfRow, false);        
	document.getElementById(idOfRowClicked).className = 'darkGray';
}

function HideMenu(evt, contextMenu, isEven, idOfRow) {
	//this behaviour is different for IE and FF, so need to see what type of event fired
	try {
		if (!window) return;
		if (window.event) { //IE
			if (window.event.toElement.parentNode.id == contextMenu.id || window.event.toElement.id == contextMenu.id) {
				//only wanna hide the menu if it's the menu we're leaving not each menu item
				return;
			}
		}
		else {//FF
			if (evt.relatedTarget.id == contextMenu.id || evt.relatedTarget.parentNode.id == contextMenu.id) {
				return;
			}
		}

		contextmenuIsShowing = false;
		var x = document.getElementById(contextMenu.id);
		x.style.display = 'none';            
		document.getElementById(idOfRow).className = (isEven) ? 'even' : '';
	}
	catch (e) { }            
}

	
	
function SelectOrDeselectAllRows(nameOfRepeater, nameOfRow, selectAllLinkId, deselectAllLinkId) {
	//Only need the name of the repeater, not the client id. Same for the name of the row
	//Do need the client ids of the links though        
	var selectAllLink = document.getElementById(selectAllLinkId);
	var deselectAllLink = document.getElementById(deselectAllLinkId);               
		

	//if the deselct button is not showing, assume we are selecting
	var selecting = (deselectAllLink.style.display == 'none');

	SelectDeselectAllRows_helperMethod(nameOfRepeater, nameOfRow, selecting);        

	if (selecting) {
		selectAllLink.style.display = 'none';
		deselectAllLink.style.display = 'inline';
	}
	else {
		selectAllLink.style.display = 'inline';
		deselectAllLink.style.display = 'none';
	}
		
	DisplayCorrectBottomLinks();        
}


function SelectDeselectAllRows_helperMethod(nameOfRepeater, nameOfRow, selectYN) {
		
	//get all the elements and look for teh repeater
	var all = document.getElementsByTagName("body")[0].getElementsByTagName("*");
	var selecting = selectYN.toString().toLowerCase() == 'true' || selectYN; //in case we pass in string or bool

	for (i = 0; i < all.length; i++) {
		elem = all[i];
		if (elem.id.indexOf(nameOfRepeater) >= 0) {
			//search for checkboxes in the repeater
			if (elem.type == 'checkbox') {                    
				if (selecting == true) {
					if (elem.checked == false) {
						elem.checked = true;
						numRowsSelected++;
					}
				}
				else {
					if (elem.checked == true) {
						elem.checked = false;
						numRowsSelected--;
					}
				}
			}
			if (elem.id.indexOf(nameOfRow) >= 0) {                    
				if (selecting == true) {
					elem.className = 'darkGray'
				}
				else {
					rowCounter++;
					if (rowCounter % 2 == 0)
						elem.className = '';
					else {
						elem.className = 'even';
					}
				}
			}
		}
	}

	rowCounter = 0;
}



	

function getY( oElement )
{
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetTop;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}




function getX(oElement) {
	var iReturnValue = 0;
	while (oElement != null) {
		iReturnValue += oElement.offsetLeft;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

function findPos(obj) {
	var left = getX(obj);
	var top = getY(obj);
	return [left, top];
}


function setElementFocus(controlid) {
    var cont = $('#' + controlid);
    cont.focus();
}


///<summary>
///As text is changed in an input field, update the total amount in another column
///</summary>
function updateQuoteRowTotalPrice(price, qty, controlToUpdate) {

    price = (isNaN(price) || price < 0) ? 0 : price;
    var divUpdate = $('#' + controlToUpdate);

    if (divUpdate.length) {
        var calcdPrice = ((price * 100) * qty) / 100;
        divUpdate.text("$" + calcdPrice.toFixed(2));
    }
}

///<summary>
///Disable the timer firing on the hub pages
///</summary>
function disableTimer() {
    if (timer != null) {
        timer._stopTimer();
    }
    return true;
}


///<summary>
///Set focus on a given object
///</summary>
function SetElementFocus(id) {
	var elem = $('#' + id);
	if (elem.length && elem.focus) {
	    elem.focus();
	    return false;
	}
}


///<summary>
///Find a given element
///</summary>
function GetElement(id) {
	return $('#' + id);
}




///<summary>
///Adjust the row color of a row in a table highlighted
///</summary>
function HighlightRow() {
    jQuery(this).css('backgroundColor', '#B5B5B5');
}

///<summary>
/// Adjust the row color of a row in a table lowlighted
///</summary>
function LowlightRow() {
     jQuery(this).css('backgroundColor',  '#D8D5CF');
}



///<summary>
/// Call button server-side click
///</summary>
function CallButtonServersideEvent(btnPressedClientId) {
	$('#' + btnPressedClientId).click();
}    


///<summary>
/// helper used to select a checkbox when text is clicked where there is text next to it
///</summary>
function selectChkBoxWhenTextIsClicked(chkBoxId) {
    var chkBox = $('#' + chkBoxId);   
    if(chkBox.length)
        chkBox.attr('checked', !(chkBox.is(':checked')));
}



///<summary>
/// handle the loadup of role checkboxes on the edit company details page 
///</summary>
function HandleRoleCheckboxLoadup() {
    var cboxes = $(roleCheckboxSelector + ':checked');
    
    for (var x = 0; x < cboxes.length; x++) {
        var curCBox = cboxes[x];
        jQuery.data(curCBox, 'CheckedAtLoadup', true);
    }
}


///<summary>
/// check whether the system administrator has removed roles from a company or not.  
/// if so, then ask them to verify this change.  If they decline it, then put all the checkboxes back
/// which they removed.
///</summary>
function EnsureUserWantsToRemoveRole() {
    var retVal = true;
    var matches = new Array();
    if (isSysAdmin) {
        //get all the checked checkboxes
        var cboxes = $(roleCheckboxSelector +':not(:checked)');
        for (var x = 0; x < cboxes.length; x++) {
        var curCheckbox = cboxes[x];
            if (jQuery.data(curCheckbox, 'CheckedAtLoadup') == true) {
                matches[matches.length] = curCheckbox.id;
            }
        }
    }
    if (matches.length > 0) {
        retVal = confirm("You have removed one or more roles for this company.  Removing a role from a company will also remove this role for all company users who are already assigned to the role.  Are you sure you want to do this?");
        //if the user has canceled the save, then repopulate the roles they have unchecked
        if (!retVal) {
            for (var y = 0; y < matches.length; y++) {
                var curOldChecker = $('#' + matches[y]).attr('checked', true);
            }
            this.beenClicked = retVal = false;
        } else {
            retVal = true;
        }
    } else {
        retVal = true;
    }
    return retVal;
}






///<summary>
///Confirm the supplier wishes to change their quote type
///</summary>
function ConfirmChangeQuoteType() {
    var control = $('#' + this.id);
    var curChecked = $('#QuoteTypeSelector input:radio:checked');
    var previousSelectedCheckbox = $('#QuoteTypeSelector').data('QuoteTypeSelectedAtLoad');
    //otherwise, confirm the user wants to do this
    if (dataHasChanged) {
        if (confirm("Are you sure you want to change the quote type? Proceeding will result in all the entered data being lost.")) {
            dataHasChanged = false;
            previousSelectedCheckbox.removeAttr("checked");
            control.attr('checked', 'checked');
            $("#aspnetForm").submit();
        } else {
            control.removeAttr("checked");
            previousSelectedCheckbox.attr('checked', 'checked');
            return false;
        }
    } else {
        $("#aspnetForm").submit();
        return true;
    }
}




///<summary>
/// Allows the user to double-post
/// the form on the page
///</summary>
jQuery.fn.allowRepostForThisPage = function() {
   jQuery(this).data('AllowRepost', true);
}



function GetFormRepostState() {
    return $("#aspnetForm").data('AllowRepost');

}


///<summary>
/// Stops the user from double-submitting
/// the form
///</summary>
jQuery.fn.preventDoubleSubmit = function () {
    jQuery(this).submit(function () {
        //if the page has been set to allow repost, then let it happen
        if (GetFormRepostState() == true) {
            return true;
        } else {
            //otherwise track the user's behaviour so no repost can happen
            if (this.beenSubmitted) {
                return false;

            } else {
                //console.log('first submit coming through');
                this.beenSubmitted = true;
            }
        }
    });
};


///<summary>
/// Stops the user from double-clicking 
/// the buttons
///</summary>
jQuery.fn.preventDoubleClick = function () {
    jQuery(this).click(function () {
        if (GetFormRepostState() == true) {
        } else {
            //otherwise track the user's behaviour so no repost can happen
            if (this.beenClicked) {
                return false;

            } else {
                //console.log('first submit coming through');
                this.beenClicked = true;
            }
        }
    });
};





function PTApplicationInit() {
    //disable double-posts
	$("#aspnetForm").preventDoubleSubmit();
	$('input[type=image]').preventDoubleClick();
	
    //rollover menus highlight / lowlight
	$('.menuItem.highlightable').mouseover(HighlightRow);
	$('.menuItem.highlightable').mouseleave(LowlightRow);
}




$(document).ready(PTApplicationInit);









