/* 
 This file was generated by Dashcode and is covered by the 
 license.txt included in the project.  You may edit this file, 
 however it is recommended to first turn off the Dashcode 
 code generator otherwise the changes will be lost.
 */

// Note: Properties and methods beginning with underbar ("_") are considered private and subject to change in future Dashcode releases.
PushButton.DISABLED_OPACITY = 0.5;

PushButton.IMAGE_POSITION_NONE = 0;
PushButton.IMAGE_POSITION_LEFT = 1;
PushButton.IMAGE_POSITION_RIGHT = 2;
PushButton.IMAGE_POSITION_TOP = 3;
PushButton.IMAGE_POSITION_BOTTOM = 4;
PushButton.IMAGE_POSITION_CENTER = 5;

PushButton.STATE_OFF = 0;
PushButton.STATE_ON = 1;


function CreatePushButton(elementOrID, spec)
{
    var buttonElement = elementOrID;
    if (elementOrID.nodeType != Node.ELEMENT_NODE) {
        buttonElement = document.getElementById(elementOrID);
    }
    
	if (!buttonElement.loaded) {
		buttonElement.loaded = true;
		buttonElement.object = new PushButton(buttonElement, spec);
	}
    
    return buttonElement.object;
}


function PushButton(buttonElement, spec)
{
	var _self = this;
    if (!buttonElement || !spec) return;
    
	this.element = buttonElement;
    
	// when cloning template, get size from original
	var styleElement = buttonElement;
    if (spec.originalID) {
        styleElement = document.getElementById(spec.originalID);
        // We need to remove any existing children when cloning
        while (buttonElement.firstChild) 
            buttonElement.removeChild(buttonElement.firstChild);
    }
	
    // calculate sizes and margins
    this._initialWidth = spec.initialWidth || 0;
    this._initialHeight = spec.initialHeight || 0;
	this._leftImageWidth = spec.leftImageWidth || 0;
	this._rightImageWidth = spec.rightImageWidth || 0;
	this._topImageWidth = 0;
	this._bottomImageWidth = 0;
    this._containerLeft = 0;
    this._containerRight = 0;

    // determine URL of background images
    this._pressed = false;
	var imagePrefix = "Images/" + styleElement.id;
	this._bgIimageURL = imagePrefix + ".png"
	this._pressedBgImageURL = imagePrefix + "_clicked.png";
	
    // create internal elements
    var style;
    this._backgroundElement = document.createElement("div");
    style = this._backgroundElement.style;
    style.position = "absolute";
    style.top = "0px";
    style.left = "0px";
    style.right = "0px";
    style.bottom = "0px";
    this.element.appendChild(this._backgroundElement);
    this._backgroundElementPressed = this._backgroundElement.cloneNode(false);
    style = this._backgroundElementPressed.style;
    style.visibility = "hidden";
    this.element.appendChild(this._backgroundElementPressed);
    this._containerElement = this._backgroundElement.cloneNode(false);
    style = this._containerElement.style;
    style.textOverflow = "inherit";
    style.whiteSpace = "inherit";
	this.element.appendChild(this._containerElement);
	this._textElement = document.createElement("span");
    style = this._textElement.style;
	style.display = "inline";
    this._containerElement.appendChild(this._textElement);
	this._imageElement = document.createElement("img");
    style = this._imageElement.style;
	style.display = "inline";
    style.verticalAlign = "middle";
    this._containerElement.appendChild(this._imageElement);
    this._lineBreakElement = document.createElement("br");
    this._containerElement.appendChild(this._lineBreakElement);
    this._eventsElement = this._backgroundElement.cloneNode(false);
    style = this._eventsElement.style;
    this.element.appendChild(this._eventsElement);

    // set the text and image values
    this._updateBackgroundImage();
	var text = spec.text || '';
	if (window.dashcode && dashcode.getLocalizedString) text = dashcode.getLocalizedString(text);
    this.setText(text);
    this.setImageURL(spec.customImage || '');
    this.setPressedImageURL(spec.customImagePressed || '');
    var imagePosition = (spec.customImagePosition == undefined) || (spec.customImagePosition.length < 1) ? PushButton.IMAGE_POSITION_NONE : eval(spec.customImagePosition);
	this.setImagePosition(imagePosition);

	// For JavaScript event handlers
	this.buttonEventHandler = dashcode.CreateTouchButtonEventHandler(this._eventsElement);
	this.enabled = !spec.disabled;
	if (this.enabled) {
		try { this.buttonEventHandler.setActionCallback(eval(spec.onclick)) } catch (e) { }
	} else {
		this.buttonEventHandler.eventsEnabled = false;
	}
	
	this.buttonEventHandler.highlightCallback = function(pressed) { _self._setPressed(pressed) };
    
    // So that some can assign the "onclick" handler for the button at runtime
    this.__defineSetter__("onclick", function(onclick){
                          this.buttonEventHandler.setActionCallback(onclick);
                          });
    
	this.__defineGetter__("onclick", function(){
                          return this.buttonEventHandler.actionCallback;
                          });
}

PushButton.prototype.setEnabled = function(enabled)
{
	// ensure 'enabled' is a boolean
	enabled = !(!enabled);
    
	if (this.enabled == enabled) {
		return;
	} 
	
	this.enabled = enabled;
	var originalOpacity = 1;
	
	var style = document.defaultView.getComputedStyle(this.element, null);
	if (style) {
		originalOpacity = +style.getPropertyValue("opacity");
	}
	
	if (enabled) {
		this.element.style.opacity = originalOpacity * (1/PushButton.DISABLED_OPACITY);
		this.buttonEventHandler.eventsEnabled = true;
		this.element.style.appleDashboardRegion = "dashboard-region(control rectangle)";
	} else {
		this.element.style.opacity = PushButton.DISABLED_OPACITY * originalOpacity;
		this.element.style.appleDashboardRegion = "none";
		this.buttonEventHandler.eventsEnabled = false;
	}
}

PushButton.prototype.setText = function(text) 
{
   this._textElement.innerText = text;
}


PushButton.prototype.getText = function()
{
	return this._textElement.innerText;
}

PushButton.prototype.sizeToFit = function(minWidth,maxWidth)
{
	var minWidthToFit = this._widthRequiredToFit();
	
	if( maxWidth && (maxWidth < minWidthToFit) ){
		minWidthToFit = parseInt(maxWidth);
	}else if( minWidth && (minWidth > minWidthToFit) ){
		minWidthToFit = parseInt(minWidth);
	}
	
	this.element.style.width = minWidthToFit + "px";	
	this._layoutElements();
}

PushButton.prototype.setImagePosition = function(position)
{
	this._imagePosition = position;
	this._layoutElements();
}

PushButton.prototype.getImagePosition = function()
{
	return this._imagePosition;
}

PushButton.prototype.setImageURL = function(imageURL)
{
    this._customImageURL = imageURL;
    this._customImageLoaded = false;
    if (this._customImageURL) {
        this._customImage = new Image();
        var _self = this;
        this._customImage.onload = function () {
            _self._customImageLoaded = true;
            _self._setCustomImage();
        }
        this._customImage.src = this._customImageURL;
	}  else {
		this._customImage = null;
		this._setCustomImage();
	}  
}

PushButton.prototype.getImageURL = function()
{
	 return this._customImageURL;
}

PushButton.prototype.setPressedImageURL = function(imageURL)
{
    this._customImagePressedURL = imageURL;
    this._customImagePressedLoaded = false;
    if (this._customImagePressedURL) {
        this._customImagePressed = new Image();
        var _self = this;
        this._customImagePressed.onload = function () {
            _self._customImagePressedLoaded = true;
            _self._setCustomImage();
        }
        this._customImagePressed.src = this._customImagePressedURL;
	}  else {
		this._customImagePressed = null;
		this._setCustomImage();
    }
}

PushButton.prototype.getPressedImageURL = function()
{
    return this._customImagePressedURL;
}

PushButton.prototype.setState = function(state)
{
    this._pressed = (state == PushButton.STATE_ON);
    // show the normal or pressed background (and custom image)
    if (this._pressed) {
        this._backgroundElement.style.visibility = "hidden";
        this._backgroundElementPressed.style.visibility = "visible";
    } else {
        this._backgroundElement.style.visibility = "visible";
        this._backgroundElementPressed.style.visibility = "hidden";
    }
	this._setCustomImage();
    // Work-around for WebKit issue 5882457, otherwise, sometimes the image position on the button can be incorrect.
    this._imageElement.offsetLeft;
}

PushButton.prototype.getState = function()
{
    return this._pressed ? PushButton.STATE_ON : PushButton.STATE_OFF;
}

/*********************
 * Private handlers
 *********************/

PushButton.prototype._setCustomImage = function()
{
    var imageStyle = this._imageElement.style;
    if (this._pressed && this._customImagePressed && this._customImagePressedLoaded) {
        this._imageElement.src = this._customImagePressedURL;
        imageStyle.width = this._customImagePressed.width + "px";
        imageStyle.height = this._customImagePressed.height + "px";
    } else if (!this._pressed && this._customImage && this._customImageLoaded) {
        this._imageElement.src = this._customImageURL;
        imageStyle.width = this._customImage.width + "px";
        imageStyle.height = this._customImage.height + "px";
    } else {
		this._imageElement.src = null;
	}
    this._layoutElements();
}

PushButton.prototype._setPressed = function(pressed)
{
    var state = pressed ? PushButton.STATE_ON : PushButton.STATE_OFF;
    this.setState(state);
}

PushButton.prototype._updateBackgroundImage = function()
{
    // determine the repeat style to use
    if (!PushButton._webKitVersion) {
        PushButton._webKitVersion = 0;
        var webKitFields = RegExp("( AppleWebKit/)([^ ]+)").exec(navigator.userAgent);
        if (webKitFields && webKitFields.length >= 3) {
            var versionString = webKitFields[2];
            var invalidCharacter = RegExp("[^\\.0-9]").exec(versionString);
            if (invalidCharacter) versionString = versionString.slice(0, invalidCharacter.index);
            PushButton._webKitVersion = +versionString.split(".")[0];
        }
    }
    var repeatStyle = PushButton._webKitVersion >= 523 ? "repeat stretch" : "stretch stretch";

    // set the background image or border image
    var borderWidth = "" + this._topImageWidth + "px " + this._rightImageWidth + "px " +  this._bottomImageWidth + "px " + this._leftImageWidth + "px";
    this._backgroundElement.style.borderWidth = borderWidth;
    this._backgroundElementPressed.style.borderWidth = borderWidth;
    if (this._leftImageWidth > 0 || this._rightImageWidth > 0) {
        this._backgroundElement.style.webkitBorderImage = "url(" + this._bgIimageURL + ") " + this._topImageWidth + " " + this._rightImageWidth + " " + this._bottomImageWidth + " " + this._leftImageWidth + " " + repeatStyle;
        this._backgroundElement.style.backgroundImage = "";
        this._backgroundElementPressed.style.webkitBorderImage = "url(" + this._pressedBgImageURL + ") " + this._topImageWidth + " " + this._rightImageWidth + " " + this._bottomImageWidth + " " + this._leftImageWidth + " " + repeatStyle;
        this._backgroundElementPressed.style.backgroundImage = "";
    } else {
        this._backgroundElement.style.webkitBorderImage = "";
        this._backgroundElement.style.backgroundImage = "url(" + this._bgIimageURL + ")";
        this._backgroundElement.style.backgroundRepeat = "repeat-x";
        this._backgroundElementPressed.style.webkitBorderImage = "";
        this._backgroundElementPressed.style.backgroundImage = "url(" + this._pressedBgImageURL + ") ";
        this._backgroundElementPressed.style.backgroundRepeat = "repeat-x";
    }

    var minMargin = 2;
    this._containerLeft = +this._leftImageWidth + minMargin;
    this._containerRight = +this._rightImageWidth + minMargin;
    if (this._containerLeft > this._containerRight) {
        this._containerLeft = Math.ceil((this._containerRight + this._containerLeft) / 2);
    } else if (this._containerRight > this._containerLeft) {
        this._containerRight = Math.ceil((this._containerRight + this._containerLeft) / 2);
    }
    this._containerElement.style.marginLeft = this._containerLeft + "px";
    this._containerElement.style.marginRight = this._containerRight + "px";
}

PushButton.prototype._layoutElements = function() {
    var position = this._imagePosition;
    if (!this._customImageLoaded && !this._customImagePressedLoaded) {
        position = PushButton.IMAGE_POSITION_NONE;
    }
	var imageStyle = this._imageElement.style;
	var textStyle = this._textElement.style;
    var containerStyle = this._containerElement.style;
    var lineBreakStyle = this._lineBreakElement.style;

    var buttonHeight = this.element.offsetHeight;
    if (buttonHeight < 1) buttonHeight = this._initialHeight;
    var buttonWidth = this.element.offsetWidth;
    if (buttonWidth < 1) buttonWidth = this._initialWidth;

    // if no image
    if (position == PushButton.IMAGE_POSITION_NONE) {
        textStyle.position = "static";
        imageStyle.display = "none";
        textStyle.display = "inline";
        containerStyle.lineHeight = buttonHeight + "px";
        containerStyle.overflow = "hidden";
        containerStyle.marginTop = "";
        lineBreakStyle.display = "none";
    } else {
        // get element dimensions
        var textHeight = this._textElement.offsetHeight;
        if (textHeight < 1) {
            var style = document.defaultView.getComputedStyle(this._textElement, null);
            if (style) {
                textHeight = parseFloat(style.getPropertyValue("font-size"));
            }
        }
        var imageWidth = this._pressed ? this._customImagePressed.width : this._customImage.width;
        var imageHeight = this._pressed ? this._customImagePressed.height : this._customImage.height;
        var horizontalSpacing = 5;
        var verticalSpacing = 5;

        // lay out the text and image
        if (position == PushButton.IMAGE_POSITION_LEFT || position == PushButton.IMAGE_POSITION_RIGHT) {
            textStyle.display = "inline";
            imageStyle.display = "inline";
            imageStyle.marginTop = "";
            imageStyle.marginBottom = "";
            containerStyle.marginTop = "";
            containerStyle.lineHeight = buttonHeight + "px";
            containerStyle.overflow = "hidden";
            lineBreakStyle.display = "none";
            if (position == PushButton.IMAGE_POSITION_LEFT) {
                this._containerElement.insertBefore(this._imageElement, this._textElement);
                imageStyle.marginLeft = "";
                imageStyle.marginRight = horizontalSpacing+"px";
            } else {
                this._containerElement.insertBefore(this._textElement, this._imageElement);
                imageStyle.marginLeft = horizontalSpacing+"px";
                imageStyle.marginRight = "";
            }
        } else if(position == PushButton.IMAGE_POSITION_TOP || position == PushButton.IMAGE_POSITION_BOTTOM) {
            textStyle.display = "inline";
            imageStyle.display = "inline";
            imageStyle.marginLeft = "";
            imageStyle.marginRight = "";
            containerStyle.lineHeight = "";
            containerStyle.overflow = "hidden";
            var containerMarginTop = Math.floor((buttonHeight - (textHeight + imageHeight + verticalSpacing)) / 2);
            containerStyle.marginTop = Math.max(containerMarginTop, 0) + "px";
            lineBreakStyle.display = "inline";
            if(position == PushButton.IMAGE_POSITION_TOP) {
                imageStyle.marginTop = "";
                imageStyle.marginBottom = verticalSpacing + "px";
                this._containerElement.insertBefore(this._imageElement, this._textElement);
                this._containerElement.insertBefore(this._lineBreakElement, this._textElement);
            } else {
                imageStyle.marginTop = verticalSpacing + "px";
                imageStyle.marginBottom = "";
                this._containerElement.insertBefore(this._textElement, this._imageElement);
                this._containerElement.insertBefore(this._lineBreakElement, this._imageElement);
            }
        } else { // position IMAGE_POSITION_CENTER
            textStyle.display = "none";
            imageStyle.display = "inline";
            containerStyle.lineHeight = buttonHeight + "px";
            containerStyle.overflow = "visible";
            containerStyle.marginTop = "";
            lineBreakStyle.display = "none";
            // if the image is larger than the button, compensate to center
            var horizontalDifference = imageWidth - (buttonWidth - this._containerLeft - this._containerRight);
            var marginLeft = (horizontalDifference > 0) ? -horizontalDifference / 2 : 0;
            var verticalDifference = imageHeight - buttonHeight;
            var marginTop = (verticalDifference > 0) ? -verticalDifference / 2 : 0;
            imageStyle.marginLeft = marginLeft + "px";
            imageStyle.marginTop = marginTop + "px";
            imageStyle.marginRight = "";
            imageStyle.marginBottom = "";
        }        
    }
}

PushButton.prototype._widthRequiredToFit = function()
{
	var textWidth = this._textElement.offsetWidth;
	var width = 0;
	
	// If there is an image
	if(this._imagePosition != PushButton.IMAGE_POSITION_NONE && (this._customImageLoaded || this._customImagePressedLoaded)){
		var imageWidth = this._pressed ? this._customImagePressed.width : this._customImage.width;
		
		switch( this._imagePosition ){
			case PushButton.IMAGE_POSITION_LEFT:
			case PushButton.IMAGE_POSITION_RIGHT:
				if( this._imageElement.style.marginLeft )
					width += parseInt(this._imageElement.style.marginLeft);
				if( this._imageElement.style.marginRight )
					width += parseInt(this._imageElement.style.marginRight);
                
				width += textWidth + imageWidth;
				break;
                default:
				if( textWidth > imageWidth )
					width += textWidth;
				else
					width += imageWidth;
				break;
		}
        
	}else{ // If there is not an image
		width += textWidth;
	}
	
	width += this._containerLeft + this._containerRight;
	
	return width;
}