// Uses the atalaInitClientScript function to add a OnPageLoad to the onload event
atalaInitClientScript('OnPageLoad();');

// Uncomment to stop rendering shadows in Menus
// YAHOO.widget.Menu.prototype.onRender = function () { };

//#region Declaraions

// Labels
var Label_FileName;
var Label_PageNum;
var Label_Status;

// YUI Panels used for dialogs.
var DialogBox_Info;
var DialogBox_OpenImage;
var DialogBox_SaveTiff;
var DialogBox_SavePdf;
var DialogBox_ColorPicker;
var DialogBox_Loading;

var DialogBox_SaveImage;

// Animation objects
var Animation_Properties;
var Animation_ToolbarSlider;

// Sidebar Property objects
var Sidebar;
var SidebarProperties;

// Menus
var	AnnoContextMenu;

// Arrays used to hold the toolbar button objects and names
var Buttons;
var ButtonNames = new Array(
	'Button_OpenImage', 'Button_SaveImage', 'Button_PrintImage',
	'Button_ZoomIn', 'Button_ZoomOut', 'Button_ZoomFull',
	'Button_Pan', 'Button_Selection', 'Button_Zoom',
	'Button_Ellipse', 'Button_Highlighter', 'Button_Line', 'Button_Lines', 'Button_Freehand', 'Button_Polygon', 'Button_Rectangle', 'Button_Redaction', 'Button_ReferencedImage', 'Button_RubberStamp', 'Button_StickyNote', 'Button_Text',
	'Button_FitBest', 'Button_FitWidth',
	'Button_HolePunchRemoval', 'Button_BorderRemoval', 'Button_InverText', 'Button_LineRemoval', 'Button_SpeckRemoval', 'Button_Despeckle', 'Button_Deskew',
	'Button_SliderLeft', 'Button_SliderRight'
);

// internal variable used to keep status messages when the status
// bar shows messages while hovering the mouse over certain ui elements
var _status = '';
// internal variable used to hold the most recently selected color
var _swatch = null;
// object used to communicate with the ColorPicker, holds the IFrame
var _colorPickerFrame;
var _init = false;

//#endregion

//#region Get/set methods

// gets the dom object specified by id
function getObj(id){
	return document.getElementById(id);
}

// gets the url of the image currently open
function getImageUrl(){
	return getObj('Hidden_Url').value;
}

// sets the current working image url, and opens it
function setImageUrl(url){
	getObj('Hidden_Url').value = url;
	OpenImage(url);
}

// sets the annotation data url, and opens them
function setAnnotationDataUrl(url){
	OpenAnnotations(url);
}

// gets the current selected frame of the working image, if any
function getPageNumber(){
	var n = WebThumbnailViewer1.getSelectedIndex();
	return (n >= 0) ? n : 0;
}

// sets the current selected frame of the working image
function setPageNumber(i){
	WebThumbnailViewer1.SelectThumb(i);
}

// gets the number of frames in the current working image
function getNumberOfPages(){
	return WebThumbnailViewer1.getCount();
}

// sets the automatic zoom of the viewer
// integer expected: 0:None 1:BestFit 2:BestFitShrinkOnly 3:FitToWidth 4:FitToHeight 5:FitToImage
function setAutoZoom(i){
	WebAnnotationViewer1.setAutoZoom(i);
}

// gets the color most recently selected by the color picker dialog
function getSwatchColor(){
	var v = '';
	
	if (_swatch != null){
		v = _swatch.value;
		
		if (v.charAt(0) == '#') {
			v = v.substring(1);
		}
	}

	return v;
}

// sets the color most recently selected by the color picker dialog
// (used by the color picker dialog only, not intended to be called elsewhere)
function setSwatchColor(a, r, g, b, h, s){
	if (s != null){
		s.style.backgroundColor ='rgb(' + r + ',' + g + ',' + b + ')';
		
		var fr = (r > 128) ? 0 : 255;
		var fg = (g > 128) ? 0 : 255;
		var fb = (b > 128) ? 0 : 255;
		
		s.style.color = 'rgb(' + fr + ',' + fg + ',' + fb + ')';
		s.value = '#' + h;
	}
}

// sets the color most recently selected by the color picker dialog, and hides the dialog
// (used by the color picker dialog only, not intended to be called elsewhere)
function PickColor(a, r, g, b, h){
	setSwatchColor(a, r, g, b, h, _swatch);
	DialogBox_ColorPicker.hide();
}

function setColorPickerFrame(o){
	_colorPickerFrame = o;
}

//#endregion

//#region Initialization

function OnPageLoad(){
	setAutoZoom(AutoZoomMode.FitToWidth);
	
	InitToolBar();
	InitDialogs();
	InitAnimators();
	InitMenus();

	// Dom Objects
	Label_FileName = getObj('Label_FileName');
	Label_Status = getObj('Label_Status');
	Label_PageNum = getObj('Label_PageNum');
	Sidebar = getObj('Sidebar');
	SidebarProperties = getObj('SidebarProperties');

	ResetState();
	FixPngs();
	UpdateStatus('Ready.');

	// Event handlers
	WebAnnotationViewer1.AnnotationChanged = OnAnnotationChanged;
	WebAnnotationViewer1.AnnotationRightClicked = OnAnnotationRightClicked;
	WebAnnotationViewer1.AnnotationDoubleClicked = OnAnnotationDoubleClicked;
	WebAnnotationViewer1.ImageChanged = OnPageLoaded;
	WebAnnotationViewer1.MouseDown = OnDeselect;	
	
	WebThumbnailViewer1.SelectedIndexChanged = OnSelectedLayerChanged;
	WebThumbnailViewer1.UrlChanged = OnThumbnailUrlChanged;
	_init = true;
}

// Used to fix an odd issue with mozilla while hitting the reload button
function ResetState(){
	getObj('WebThumbnailViewer1_sbw').value = '0';
	getObj('WebThumbnailViewer1_sbh').value = '0';
}

// sets up all of the YUI dialog boxes
function InitDialogs(){
	DialogBox_Info			= new YAHOO.widget.Panel("DialogBox_Info", 			{fixedcenter:true, modal:true, visible:false, constraintoviewport:true });
	DialogBox_OpenImage		= new YAHOO.widget.Panel("DialogBox_OpenImage",		{fixedcenter:true, modal:true, visible:false, constraintoviewport:true });
	DialogBox_SaveTiff		= new YAHOO.widget.Panel("DialogBox_SaveTiff",		{fixedcenter:true, modal:true, visible:false, constraintoviewport:true });
	DialogBox_SavePdf       = new YAHOO.widget.Panel("DialogBox_SavePdf",       {fixedcenter:true, modal:true, visible:false, constraintoviewport:true }); 
	DialogBox_ColorPicker	= new YAHOO.widget.Panel("DialogBox_ColorPicker",	{fixedcenter:true, modal:true, visible:false, constraintoviewport:true });
	DialogBox_Loading		= new YAHOO.widget.Panel("waitBox",  				{fixedcenter:true, modal:true, visible:true, width:"230px", close:false, draggable:false });

	DialogBox_Loading.setHeader("Loading, please wait...");
	DialogBox_Loading.setBody('<div style="text-align:center;"><img src="yui/rel_interstitial_loading.gif" /><br/><input style="margin:4px" class="button" type="button" value="Cancel" onclick="DialogBox_Loading.hide();" /></div>');
	
	DialogBox_Info.render();
	DialogBox_OpenImage.render();
	DialogBox_SaveTiff.render();
	DialogBox_SavePdf.render();
	DialogBox_ColorPicker.render();
	DialogBox_Loading.render(document.body);
}

function InitAnimators(){
	Animation_Properties = new Object();
	Animation_ToolbarSlider = new Object();

    Animation_Properties.slideOut	= new YAHOO.util.Anim('ThumbContainer', {height:{ to:494 }}, 1, YAHOO.util.Easing.easeIn); 
    Animation_Properties.slideIn	= new YAHOO.util.Anim('ThumbContainer', {height:{ to:244 }}, 1, YAHOO.util.Easing.easeOut); 

    Animation_ToolbarSlider.slideOut= new YAHOO.util.Anim('ToolbarSlider', {width:{ to:372 }}, 1, YAHOO.util.Easing.easeIn); 
    Animation_ToolbarSlider.slideIn	= new YAHOO.util.Anim('ToolbarSlider', {width:{ to:1}}, 1, YAHOO.util.Easing.easeOut); 
}

function InitMenus(){
	AnnoContextMenu = new YAHOO.widget.Menu("AnnoContextMenu", { width:"160px"});
	AnnoContextMenu.render();
}

//#endregion

//#region Events

// show the info dialog
function OnLink_Info_Click(force){
	DialogBox_Info.show();
}

// shows the open image dialog  
function OnButton_OpenImage_Click(){
	DialogBox_OpenImage.show();
}

// shows the save image dialog
function OnButton_SaveImage_Click() {
    var path = getImageUrl();

    if (path != '') {
        if (path.match("tiff") == "tiff") {
            DialogBox_SaveImage = DialogBox_SaveTiff;
            DialogBox_SaveImage.show();
        }
        else if (path.match("pdf") == "pdf") {
        DialogBox_SaveImage = DialogBox_SavePdf;
        DialogBox_SaveImage.show();
        }
    }

}

function LoadHiddenImage(path){
    Loading(true);
    var iFrame = document.getElementById('BurnedDocumentFrame');
    if (iFrame) {
        document.body.removeChild(iFrame);
    }

	iFrame = document.createElement('iframe');
	iFrame.setAttribute('id', 'BurnedDocumentFrame');
	iFrame.style.position = 'absolute';
    iFrame.style.visibility = "hidden";

	switch (atalaCheckBrowser()){
		case 0:	// Internet Explorer
			iFrame.onreadystatechange = function(){
				if (iFrame.readyState == "complete" || iFrame.readyState == "interactive"){
					Loading(false);
				}
			};
		break;
		
		case 1: // Firefox
		case 3:	// Opera
			Loading(false);
		break;
		
		case 2:	// Safari
		case 4:	// Chrome
			iFrame.onload = function(){
				Loading(false);
			};
		break;
	}

    document.body.appendChild(iFrame);
    iFrame.src = path;
}



//use remote invoke
function OnButton_PrintImage_Click(){
    var xmpPath = WebAnnotationViewer1.getAnnotationDataUrl();
    var path = 'AJAXAnnotationsDemoExport.aspx?path=' + getImageUrl() + '&xmppath=' + xmpPath + '&command=burn';
    var str = getImageUrl();
    if (str.match("tiff") == "tiff"){
        path += '&format=tiff';
    }
    else if (str.match("pdf") == "pdf"){
        path += '&format=pdf'
    }
    path += '&p=true';
    LoadHiddenImage(path);
}

function PrintImageCallBack() {
    WebAnnotationViewer1.RemoteInvoked = function() { };
}

// shows the color picker dialog
function OnPropFillColor_Click(o){
	_swatch = o;
	ResetColorPickerColor();
	DialogBox_ColorPicker.show();
}

// only show the Selected Layer
function OnSelectedLayerChanged(){
	WebAnnotationViewer1.DeselectAll();
	Animation_Properties.slideOut.animate();
	UpdateLabel_PageNum();
}

function OnThumbnailUrlChanged(){
	UpdateStatus('Thumbnails Loading...');
	WebThumbnailViewer1.SelectThumb(0);
}

function OnPageLoaded(){
	UpdateStatus('Page Loaded.');
	window.setTimeout('UpdateStatus("Ready.");', 1500);
//	window.setTimeout('UpdateStatus("Ready.");WebAnnotationViewer1.Update();', 1500);
	Loading(false);
}

function OnAnnotationChanged(e){
	WebAnnotationViewer1.getSelection().setVisibility('hidden');
}

// fires when the selection mousetool has changed
function OnSelectionChanged(e){
	if (WebAnnotationViewer1.getCurrentLayer()){
		var r = WebAnnotationViewer1.getSelection().getRectangle();
		var anns = WebAnnotationViewer1.getCurrentLayer().getAnnotations();
	
		for (var i = 0; i < anns.length; i++)
		{
			anns[i].setSelected(__intersects(r, anns[i].getRectangle()));
		}
	}
	
	WebAnnotationViewer1.getSelection().setVisibility('hidden');
	
}

var _currentAnno = null;
function OnAnnotationRightClicked(e){
	var annoCell = getObj('annoCell');

	// change the location of the context menu
	AnnoContextMenu.moveTo(e.clientX + atalaGetOffsetLeft(annoCell), e.clientY + atalaGetOffsetTop(annoCell));
	
	if (e.annotation.getSelected() == false){
		WebAnnotationViewer1.DeselectAll();
	}
	
	e.annotation.setSelected(true);
	_currentAnno = e.annotation;
		
	AnnoContextMenu.show();
	return true;
}

function OnAnnotationDoubleClicked(e){
	if (e.annotation.getType() != 'TextData' && e.annotation.getType() != 'ReferencedImageData') {
		var annoCell = getObj('annoCell');
		AnnoProperties(e.clientX + atalaGetOffsetLeft(annoCell), e.clientY + atalaGetOffsetTop(annoCell));
	}
}

function OnDeselect(e){
 	Animation_Properties.slideOut.animate();
 	AnnoContextMenu.hide();
}

function Loading(b){
	if (b == true){
		DialogBox_Loading.show();
	}
	else {
		DialogBox_Loading.hide();
	}
}
//#endregion

//#region Toolbar

function InitToolBar(){
	// gets button objects
	Buttons = new Array();
	
	for (var i = 0; i < ButtonNames.length; i++){
		Buttons.push(getObj(ButtonNames[i]));
	}
		
	// adds click events to each button
	Buttons[0].onclick = function(){ OnButton_OpenImage_Click(); return false;};
	Buttons[1].onclick = function() { OnButton_SaveImage_Click(); return false; };
	Buttons[2].onclick = function() { OnButton_PrintImage_Click(); return false; };
	Buttons[3].onclick = function(){ setAutoZoom(0); Zoom(1); return false;};
	Buttons[4].onclick = function(){ setAutoZoom(0); Zoom(-1); return false;};
	Buttons[5].onclick = function(){ setAutoZoom(0); WebAnnotationViewer1.setZoom(1); return false;};
	Buttons[6].onclick = function(){ ChangeMouseTool(0); return false;};
	Buttons[7].onclick = function(){ ChangeMouseTool(1); return false;};
	Buttons[8].onclick = function(){ ChangeMouseTool(2); return false;};
	Buttons[9].onclick = function(){ CreateAnnotation('EllipseData',	'DefaultEllipse'); return false;};
	Buttons[10].onclick = function(){ CreateAnnotation('RectangleData',	'DefaultHighlighter'); return false;};
	Buttons[11].onclick = function(){ CreateAnnotation('LineData',		'DefaultLine'); return false;};
	Buttons[12].onclick = function(){ CreateAnnotation('LinesData',		'DefaultLines'); return false;};
	Buttons[13].onclick = function(){ CreateAnnotation('FreehandData',	'DefaultFreehand'); return false;};
	Buttons[14].onclick = function(){ CreateAnnotation('PolygonData',	'DefaultPolygon'); return false;};
	Buttons[15].onclick = function(){ CreateAnnotation('RectangleData',	'DefaultRectangle'); return false;};
	Buttons[16].onclick = function(){ CreateAnnotation('RectangleData', 'DefaultRedaction'); return false;};
	Buttons[17].onclick = function(){ CreateAnnotation('ReferencedImageData'); return false;};
	Buttons[18].onclick = function(){ CreateAnnotation('RubberStampData'); return false;};
	Buttons[19].onclick = function(){ CreateAnnotation('TextData', 'DefaultStickyNote'); return false;};
	Buttons[20].onclick = function(){ CreateAnnotation('TextData', 'DefaultTextAnnotation'); return false;};
	Buttons[21].onclick = function(){ setAutoZoom(1); return false;};
	Buttons[22].onclick = function(){ setAutoZoom(3); return false;};
	Buttons[23].onclick = function(){ Process_Image('HolePunchRemoval'); return false;};
	Buttons[24].onclick = function(){ Process_Image('BorderRemoval'); return false;};
	Buttons[25].onclick = function(){ Process_Image('InvertText'); return false;};
	Buttons[26].onclick = function(){ Process_Image('LineRemoval'); return false;};
	Buttons[27].onclick = function(){ Process_Image('SpeckRemoval'); return false;};
	Buttons[28].onclick = function(){ Process_Image('Despeckle'); return false;};
	Buttons[29].onclick = function(){ Process_Image('Deskew'); return false;};
	Buttons[30].onclick = function(){ Animation_ToolbarSlider.slideIn.animate(); return false;};
	Buttons[31].onclick = function(){ Animation_ToolbarSlider.slideOut.animate(); return false;};

	// sets up button rollover effect
	for (var i = 0; i < Buttons.length; i++){
		FixPng(Buttons[i].src, Buttons[i]);
		
		Buttons[i].onmouseover = function(){ this.parentNode.className = 'buttonIn'; _status = Label_Status.innerHTML; UpdateStatus(this.title);};
		Buttons[i].onmouseout = function(){ this.parentNode.className = 'buttonOut'; UpdateStatus(_status);};
		Buttons[i].onmousedown = function(){ this.parentNode.className = 'buttonDown';};
		Buttons[i].onmouseup = function(){ this.parentNode.className = 'buttonIn';};
	}
}

//#endregion

//#region Context Menu Functions

function DeleteAnno()
{
	Animation_Properties.slideOut.animate();

	var anns = WebAnnotationViewer1.getSelectedAnnotations();
	WebAnnotationViewer1.DeleteAnnotations(anns);
}

function MoveSelectedAnnoToPos(i)
{
	var layer = _currentAnno.getParent();
	var count = layer.getAnnotations().length;
	if (i >= 0 && i <= count) {
		layer.Insert(_currentAnno, i);
	}
}

function MoveSelectedAnnoForward()
{			
	MoveSelectedAnnoToPos(_currentAnno.getZIndex() + 1);	
}

function MoveSelectedAnnoFront()
{		
	MoveSelectedAnnoToPos(_currentAnno.getParent().getAnnotations().length);	
}

function MoveSelectedAnnoBackward()
{
	MoveSelectedAnnoToPos(_currentAnno.getZIndex() - 1);
}

function MoveSelectedAnnoBack()
{
	MoveSelectedAnnoToPos(0);
}

//#endregion

//#region Status

// Updates the 'Page # of ###' label
function UpdateLabel_PageNum(){
	if (Label_PageNum){
		Label_PageNum.innerHTML = 'Page ' + (getPageNumber() + 1) + ' of ' + getNumberOfPages();
	}
}

// Pops up a message box when an error is caught
function UpdateErrorStatus(msg){
	if (Label_Status){
		Label_Status.innerHTML = 'An Error Occured';
	}
	
	Loading(false);
	alert(msg);
}

// Sends status messages to the status label
function UpdateStatus(msg){
	if (Label_Status){
		Label_Status.innerHTML = msg;
	}
}

//#endregion

//#region Operations

// Changes the mouse behavior
function ChangeMouseTool(i){

	switch(i){
		case 0:	// Pan tool
			WebAnnotationViewer1.setMouseTool(MouseToolType.Pan);
			WebAnnotationViewer1.getSelection().Changed = function(){};
			WebAnnotationViewer1.getSelection().setVisibility('hidden');
			break;
		case 1:	//Selection tool
			WebAnnotationViewer1.setMouseTool(MouseToolType.Selection);
			WebAnnotationViewer1.getSelection().Changed = OnSelectionChanged;
			break;
		case 2:	// Zoom tool
			WebAnnotationViewer1.setMouseTool(MouseToolType.ZoomIn, MouseToolType.ZoomOut);
			setAutoZoom(AutoZoomMode.None);
			WebAnnotationViewer1.getSelection().Changed = function(){};
			WebAnnotationViewer1.getSelection().setVisibility('hidden');
			break;
	}
}

function CreateAnnotation(s, n){
	WebAnnotationViewer1.DeselectAll();
	WebAnnotationViewer1.CreateAnnotation(s, n);
}

function DownloadImage(cmd, convert) {
    DialogBox_SaveImage.hide();
    var xmpPath = WebAnnotationViewer1.getAnnotationDataUrl();
    var path = 'AJAXAnnotationsDemoExport.aspx?path=' + getImageUrl() + '&xmppath=' + xmpPath + '&command=' + cmd + '&convert=' + convert;

    if (cmd != "xmp") {
        var str = getImageUrl();
        if (str.match("tiff") == "tiff") {
            path += '&format=tiff';
        }
        else if (str.match("pdf") == "pdf") {
            path += '&format=pdf'
        }
    }
    else {
        path += '&format=xml';
    }
    path += '&p=false';
    LoadHiddenImage(path);
}

// Increments and decrements the zoom level
function Zoom(inOut){
	var z = WebAnnotationViewer1.getZoom();
	var zp = WebAnnotationViewer1.getZoomInOutPercentage();
	
	z += inOut * z * zp / 100;
	WebAnnotationViewer1.setZoom(z);
}

// Uses RemoteInvoke to process the entire image
function Process_Image(cmd){
	WebAnnotationViewer1.RemoteInvoked = ProcessImageCallBack;
	WebAnnotationViewer1.RemoteInvoke('Remote_ProcessImage', new Array(cmd));
}

function ProcessImageCallBack(){
	WebAnnotationViewer1.RemoteInvoked = function(){};
	WebThumbnailViewer1.UpdateThumb(WebThumbnailViewer1.getSelectedIndex());
}

function OpenImage(url) {
	WebAnnotationViewer1.RemoteInvoked = OpenImageCallBack;
	WebAnnotationViewer1.RemoteInvoke('Remote_OpenImage', new Array(url));
}

function OpenImageCallBack() {
    WebAnnotationViewer1.RemoteInvoked = function() { };
    WebThumbnailViewer1.OpenUrl(WebAnnotationViewer1.getReturnValue());
	Label_FileName.innerHTML = WebThumbnailViewer1.getUrl();
	UpdateAnnoMenu(WebThumbnailViewer1.getUrl());
}

function UpdateAnnoMenu(url) {
        if (url.indexOf(".pdf") != -1) {
            for (var i = 23; i < 30; i++) {
                var buttonUrl = Buttons[i].src;
                if (buttonUrl.indexOf("Disabled") == -1) {
                    var newImageUrl = buttonUrl.slice(0, buttonUrl.indexOf(".png"));
                    newImageUrl = newImageUrl + "Disabled.png";
                    Buttons[i].src = newImageUrl;
                }
                Buttons[i].disabled = true;
            }
        }
        else if (url.indexOf(".tiff") != -1) {
            for (var i = 23; i < 30; i++) {
                var buttonUrl = Buttons[i].src;
                if (buttonUrl.indexOf("Disabled") != -1) {
                    var newImageUrl = buttonUrl.slice(0, buttonUrl.indexOf("Disabled.png"));
                    newImageUrl = newImageUrl + ".png";
                    Buttons[i].src = newImageUrl;
                    Buttons[i].disabled = false;
                }
            }

        }
    
}


function OpenAnnotations(url){
	WebAnnotationViewer1.RemoteInvoked = OpenAnnotationsCallBack;
	WebAnnotationViewer1.RemoteInvoke('Remote_OpenAnnotations', new Array(url));
}

function OpenAnnotationsCallBack(){
    WebAnnotationViewer1.RemoteInvoked = function() { };
    Loading(false);
}

function ResetColorPickerColor(){
	if (_colorPickerFrame && _colorPickerFrame.ResetColor){
		_colorPickerFrame.ResetColor();
	}
}

//#endregion

//#region Helper Functions

// converts one hexidecimal into an integer
function hex2int(hex) {
	var t = '0123456789ABCDEF';
	return t.indexOf(hex.toUpperCase());
}

// converts a hex color value into an argb string usable by css styles
function hex2argb(str) { 
	 var argb = [];
	 var offset = 0;
	 
	 if (str.length == 8){
	 	argb[0] = (hex2int(str.substr(offset, 1)) * 16) + hex2int(str.substr(offset + 1, 1));
	 	offset += 2;
	 }
	 else {
		 argb[0] = 255;
	 }
	 
	 if (str.length > 1){
	 	argb[1] = (hex2int(str.substr(offset	, 1)) * 16) + hex2int(str.substr(offset + 1, 1));
	 	argb[2] = (hex2int(str.substr(offset + 2, 1)) * 16) + hex2int(str.substr(offset + 3, 1));
	 	argb[3] = (hex2int(str.substr(offset + 4, 1)) * 16) + hex2int(str.substr(offset + 5, 1));
	 }
	 else{
	 	argb[1] = 0;
	 	argb[2] = 0;
	 	argb[3] = 0;
	 }
	 
	 return argb;
}

// determines whether atalaRectangle r1 intersects with atalaRectangle r2
function __intersects(r1, r2){
	return ((r2.X >= r1.X) && (r2.Y >= r1.Y) && (r2.X <= r1.X + r1.Width) && (r2.Y <= r1.Y + r1.Height)) && ((r2.X + r2.Width <= r1.X + r1.Width) && (r2.Y + r2.Height <= r1.Y + r1.Height));
}

//#endregion

//#region PNG Transparency

// fixes all images on the page with the .png extension if needed
// (for IE 5.5 and 6.0 PNG transparency problem)
function FixPngs(){
	if (NeedsPngFix()){
		for (i = 0; i < document.images.length; i++){
			var s = document.images[i].src;
			if (s.indexOf('.png') > 0)
				FixPng(s, document.images[i]);
		}
	}
}

// replaces the original img object's src attribute with a spacer.gif
// and adds the alpha image loader filter with the original img.src
// (for IE 5.5 and 6.0 PNG transparency problem)
function FixPng(u, d){
	if (NeedsPngFix()){
		d.src = 'Skin/spacer.gif';
		d.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + u + "', sizingMethod='scale')";
	}
}

// checks if the browser is IE, and determines if it's a version that needs
// to fix the alpha transparency of PNG images
function NeedsPngFix(){
	return (navigator.userAgent.indexOf('MSIE') > 0 && navigator.userAgent.indexOf('MSIE 7.0') < 0)
}

//#endregion
