﻿/**
 * appendDom - Extremely flexible tool for dynamic dom creation.
 *   http://byron-adams.com/projects/jquery/appendDom
 *
 * Copyright (c) 2007 Byron Adams (http://byron-adams.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 */
jQuery.fn.appendDom = function(template) {
  return this.each(function() {
    for (element in template) {
      var el = (typeof(template[element].tagName) === 'string') ?
        document.createElement(template[element].tagName): document.createTextNode('');
      delete template[element].tagName;
      for (attrib in template[element]) {
        switch ( typeof(template[element][attrib]) ) {
          case 'string' :
            if ( typeof(el[attrib]) === 'string' ) {          
             el[attrib] = template[element][attrib];
            } else {
              el.setAttribute(attrib, template[element][attrib]);
            }
            break;
          case 'function':
            el[attrib] = template[element][attrib];
            break;
          case 'object' :
            if (attrib === 'childNodes')  {$(el).appendDom(template[element][attrib]);}
            break;
        }
      }
      this.appendChild(el);
    }
  });
};

/**
 * Flash (http://jquery.lukelutman.com/plugins/flash)
 * A jQuery plugin for embedding Flash movies.
 * 
 * Version 1.0
 * November 9th, 2006
 *
 * Copyright (c) 2006 Luke Lutman (http://www.lukelutman.com)
 * Dual licensed under the MIT and GPL licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/gpl-license.php
 * 
 * Inspired by:
 * SWFObject (http://blog.deconcept.com/swfobject/)
 * UFO (http://www.bobbyvandersluis.com/ufo/)
 * sIFR (http://www.mikeindustries.com/sifr/)
 * 
 * IMPORTANT: 
 * The packed version of jQuery breaks ActiveX control
 * activation in Internet Explorer. Use JSMin to minifiy
 * jQuery (see: http://jquery.lukelutman.com/plugins/flash#activex).
 *
 **/ 
;(function(){
	
var $$;

/**
 * 
 * @desc Replace matching elements with a flash movie.
 * @author Luke Lutman
 * @version 1.0.1
 *
 * @name flash
 * @param Hash htmlOptions Options for the embed/object tag.
 * @param Hash pluginOptions Options for detecting/updating the Flash plugin (optional).
 * @param Function replace Custom block called for each matched element if flash is installed (optional).
 * @param Function update Custom block called for each matched if flash isn't installed (optional).
 * @type jQuery
 *
 * @cat plugins/flash
 * 
 * @example $('#hello').flash({ src: 'hello.swf' });
 * @desc Embed a Flash movie.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { version: 8 });
 * @desc Embed a Flash 8 movie.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { expressInstall: true });
 * @desc Embed a Flash movie using Express Install if flash isn't installed.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { update: false });
 * @desc Embed a Flash movie, don't show an update message if Flash isn't installed.
 *
**/
$$ = jQuery.fn.flash = function(htmlOptions, pluginOptions, replace, update) {
	
	// Set the default block.
	var block = replace || $$.replace;
	
	// Merge the default and passed plugin options.
	pluginOptions = $$.copy($$.pluginOptions, pluginOptions);
	
	// Detect Flash.
	if(!$$.hasFlash(pluginOptions.version)) {
		// Use Express Install (if specified and Flash plugin 6,0,65 or higher is installed).
		if(pluginOptions.expressInstall && $$.hasFlash(6,0,65)) {
			// Add the necessary flashvars (merged later).
			var expressInstallOptions = {
				flashvars: {  	
					MMredirectURL: location,
					MMplayerType: 'PlugIn',
					MMdoctitle: jQuery('title').text() 
				}					
			};
		// Ask the user to update (if specified).
		} else if (pluginOptions.update) {
			// Change the block to insert the update message instead of the flash movie.
			block = update || $$.update;
		// Fail
		} else {
			// The required version of flash isn't installed.
			// Express Install is turned off, or flash 6,0,65 isn't installed.
			// Update is turned off.
			// Return without doing anything.
			return this;
		}
	}
	
	// Merge the default, express install and passed html options.
	htmlOptions = $$.copy($$.htmlOptions, expressInstallOptions, htmlOptions);
	
	// Invoke $block (with a copy of the merged html options) for each element.
	return this.each(function(){
		block.call(this, $$.copy(htmlOptions));
	});
	
};
/**
 *
 * @name flash.copy
 * @desc Copy an arbitrary number of objects into a new object.
 * @type Object
 * 
 * @example $$.copy({ foo: 1 }, { bar: 2 });
 * @result { foo: 1, bar: 2 };
 *
**/
$$.copy = function() {
	var options = {}, flashvars = {};
	for(var i = 0; i < arguments.length; i++) {
		var arg = arguments[i];
		if(arg == undefined) continue;
		jQuery.extend(options, arg);
		// don't clobber one flash vars object with another
		// merge them instead
		if(arg.flashvars == undefined) continue;
		jQuery.extend(flashvars, arg.flashvars);
	}
	options.flashvars = flashvars;
	return options;
};
/*
 * @name flash.hasFlash
 * @desc Check if a specific version of the Flash plugin is installed
 * @type Boolean
 *
**/
$$.hasFlash = function() {
	// look for a flag in the query string to bypass flash detection
	if(/hasFlash\=true/.test(location)) return true;
	if(/hasFlash\=false/.test(location)) return false;
	var pv = $$.hasFlash.playerVersion().match(/\d+/g);
	var rv = String([arguments[0], arguments[1], arguments[2]]).match(/\d+/g) || String($$.pluginOptions.version).match(/\d+/g);
	for(var i = 0; i < 3; i++) {
		pv[i] = parseInt(pv[i] || 0);
		rv[i] = parseInt(rv[i] || 0);
		// player is less than required
		if(pv[i] < rv[i]) return false;
		// player is greater than required
		if(pv[i] > rv[i]) return true;
	}
	// major version, minor version and revision match exactly
	return true;
};
/**
 *
 * @name flash.hasFlash.playerVersion
 * @desc Get the version of the installed Flash plugin.
 * @type String
 *
**/
$$.hasFlash.playerVersion = function() {
	// ie
	try {
		try {
			// avoid fp6 minor version lookup issues
			// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
			var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
			try { axo.AllowScriptAccess = 'always';	} 
			catch(e) { return '6,0,0'; }				
		} catch(e) {}
		return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
	// other browsers
	} catch(e) {
		try {
			if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
				return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
			}
		} catch(e) {}		
	}
	return '0,0,0';
};
/**
 *
 * @name flash.htmlOptions
 * @desc The default set of options for the object or embed tag.
 *
**/
$$.htmlOptions = {
	height: 240,
	flashvars: {},
	pluginspage: 'http://www.adobe.com/go/getflashplayer',
	src: '#',
	type: 'application/x-shockwave-flash',
	width: 320		
};
/**
 *
 * @name flash.pluginOptions
 * @desc The default set of options for checking/updating the flash Plugin.
 *
**/
$$.pluginOptions = {
	expressInstall: false,
	update: true,
	version: '6.0.65'
};
/**
 *
 * @name flash.replace
 * @desc The default method for replacing an element with a Flash movie.
 *
**/
$$.replace = function(htmlOptions) {
	this.innerHTML = '<div class="alt">'+this.innerHTML+'</div>';
	jQuery(this)
		.addClass('flash-replaced')
		.prepend($$.transform(htmlOptions));
};
/**
 *
 * @name flash.update
 * @desc The default method for replacing an element with an update message.
 *
**/
$$.update = function(htmlOptions) {
	var url = String(location).split('?');
	url.splice(1,0,'?hasFlash=true&');
	url = url.join('');
	var msg = '<p>This content requires the Flash Player. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a>. Already have Flash Player? <a href="'+url+'">Click here.</a></p>';
	this.innerHTML = '<span class="alt">'+this.innerHTML+'</span>';
	jQuery(this)
		.addClass('flash-update')
		.prepend(msg);
};
/**
 *
 * @desc Convert a hash of html options to a string of attributes, using Function.apply(). 
 * @example toAttributeString.apply(htmlOptions)
 * @result foo="bar" foo="bar"
 *
**/
function toAttributeString() {
	var s = '';
	for(var key in this)
		if(typeof this[key] != 'function')
			s += key+'="'+this[key]+'" ';
	return s;		
};
/**
 *
 * @desc Convert a hash of flashvars to a url-encoded string, using Function.apply(). 
 * @example toFlashvarsString.apply(flashvarsObject)
 * @result foo=bar&foo=bar
 *
**/
function toFlashvarsString() {
	var s = '';
	for(var key in this)
		if(typeof this[key] != 'function')
			s += key+'='+encodeURIComponent(this[key])+'&';
	return s.replace(/&$/, '');		
};
/**
 *
 * @name flash.transform
 * @desc Transform a set of html options into an embed tag.
 * @type String 
 *
 * @example $$.transform(htmlOptions)
 * @result <embed src="foo.swf" ... />
 *
 * Note: The embed tag is NOT standards-compliant, but it 
 * works in all current browsers. flash.transform can be
 * overwritten with a custom function to generate more 
 * standards-compliant markup.
 *
**/
$$.transform = function(htmlOptions) {
	htmlOptions.toString = toAttributeString;
	if(htmlOptions.flashvars) htmlOptions.flashvars.toString = toFlashvarsString;
	return '<embed ' + String(htmlOptions) + '/>';		
};

/**
 *
 * Flash Player 9 Fix (http://blog.deconcept.com/2006/07/28/swfobject-143-released/)
 *
**/
if (window.attachEvent) {
	window.attachEvent("onbeforeunload", function(){
		__flash_unloadHandler = function() {};
		__flash_savedUnloadHandler = function() {};
	});
}

})();

/**
* jQuery lightBox plugin
* This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
* and adapted to me for use like a plugin from jQuery.
* @name jquery-lightbox-0.5.js
* @author Leandro Vieira Pinho - http://leandrovieira.com
* @version 0.5
* @date April 11, 2008
* @category jQuery plugin
* @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
* @license CC Attribution-No Derivative Works 2.5 Brazil - http://creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
* @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin



document.getElementById('divRight').clientHeight
*/
(function($) {
    $.fn.lightBox = function(settings) {
        settings = jQuery.extend({ overlayBgColor: '#000', overlayOpacity: 0.8, fixedNavigation: false, imageLoading: 'images/lightbox-ico-loading.gif', imageBtnPrev: 'images/lightbox-btn-prev.gif', imageBtnNext: 'images/lightbox-btn-next.gif', imageBtnClose: 'images/lightbox-btn-close.gif', imageBlank: 'images/lightbox-blank.gif', containerBorderSize: 10, containerResizeSpeed: 400, txtImage: 'Image', txtOf: 'of', keyToClose: 'c', keyToPrev: 'p', keyToNext: 'n', imageArray: [], activeImage: 0 }, settings); var jQueryMatchedObj = this; function _initialize() { _start(this, jQueryMatchedObj); return false; }
        function _start(objClicked, jQueryMatchedObj) {
            $('embed, object, select').css({ 'visibility': 'hidden' }); _set_interface(); settings.imageArray.length = 0; settings.activeImage = 0; if (jQueryMatchedObj.length == 1) { settings.imageArray.push(new Array(objClicked.getAttribute('href'), objClicked.getAttribute('title'))); } else { for (var i = 0; i < jQueryMatchedObj.length; i++) { settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'), jQueryMatchedObj[i].getAttribute('title'))); } }
            while (settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href')) { settings.activeImage++; }
            _set_image_to_view();
        }
        function _set_interface() {
            $('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + settings.imageLoading + '"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="' + settings.imageBtnClose + '"></a></div></div></div></div>'); var arrPageSizes = ___getPageSize(); $('#jquery-overlay').css({ backgroundColor: settings.overlayBgColor, opacity: settings.overlayOpacity, width: arrPageSizes[0], height: arrPageSizes[1] }).fadeIn(); var arrPageScroll = ___getPageScroll(); $('#jquery-lightbox').css({ top: arrPageScroll[1] + (arrPageSizes[3] / 10), left: arrPageScroll[0] }).show(); $('#jquery-overlay,#jquery-lightbox').click(function() { _finish(); }); $('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() { _finish(); return false; }); $(window).resize(function() {
                var arrPageSizes = ___getPageSize();
                //alterado para funcionar totalHeight no IE
                if (arrPageSizes[1] < document.getElementById('divRight').clientHeight) { arrPageSizes[1] = document.getElementById('divRight').clientHeight }
                $('#jquery-overlay').css({ width: arrPageSizes[0], height: arrPageSizes[1] }); var arrPageScroll = ___getPageScroll(); $('#jquery-lightbox').css({ top: arrPageScroll[1] + (arrPageSizes[3] / 10), left: arrPageScroll[0] });
            });
        }
        function _set_image_to_view() {
            $('#lightbox-loading').show(); if (settings.fixedNavigation) { $('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide(); } else { $('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide(); }
            var objImagePreloader = new Image(); objImagePreloader.onload = function() { $('#lightbox-image').attr('src', settings.imageArray[settings.activeImage][0]); _resize_container_image_box(objImagePreloader.width, objImagePreloader.height); objImagePreloader.onload = function() { }; }; objImagePreloader.src = settings.imageArray[settings.activeImage][0];
        }; function _resize_container_image_box(intImageWidth, intImageHeight) {
            var intCurrentWidth = $('#lightbox-container-image-box').width(); var intCurrentHeight = $('#lightbox-container-image-box').height(); var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); var intDiffW = intCurrentWidth - intWidth; var intDiffH = intCurrentHeight - intHeight; $('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight }, settings.containerResizeSpeed, function() { _show_image(); }); if ((intDiffW == 0) && (intDiffH == 0)) { if ($.browser.msie) { ___pause(250); } else { ___pause(100); } }
            $('#lightbox-container-image-data-box').css({ width: intImageWidth }); $('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) });
        }; function _show_image() { $('#lightbox-loading').hide(); $('#lightbox-image').fadeIn(function() { _show_image_data(); _set_navigation(); }); _preload_neighbor_images(); }; function _show_image_data() {
            $('#lightbox-container-image-data-box').slideDown('fast'); $('#lightbox-image-details-caption').hide(); if (settings.imageArray[settings.activeImage][1]) { $('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show(); }
            if (settings.imageArray.length > 1) { $('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + (settings.activeImage + 1) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show(); }
        }
        function _set_navigation() {
            $('#lightbox-nav').show(); $('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ 'background': 'transparent url(' + settings.imageBlank + ') no-repeat' }); if (settings.activeImage != 0) { if (settings.fixedNavigation) { $('#lightbox-nav-btnPrev').css({ 'background': 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' }).unbind().bind('click', function() { settings.activeImage = settings.activeImage - 1; _set_image_to_view(); return false; }); } else { $('#lightbox-nav-btnPrev').unbind().hover(function() { $(this).css({ 'background': 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' }); }, function() { $(this).css({ 'background': 'transparent url(' + settings.imageBlank + ') no-repeat' }); }).show().bind('click', function() { settings.activeImage = settings.activeImage - 1; _set_image_to_view(); return false; }); } }
            if (settings.activeImage != (settings.imageArray.length - 1)) { if (settings.fixedNavigation) { $('#lightbox-nav-btnNext').css({ 'background': 'url(' + settings.imageBtnNext + ') right 15% no-repeat' }).unbind().bind('click', function() { settings.activeImage = settings.activeImage + 1; _set_image_to_view(); return false; }); } else { $('#lightbox-nav-btnNext').unbind().hover(function() { $(this).css({ 'background': 'url(' + settings.imageBtnNext + ') right 15% no-repeat' }); }, function() { $(this).css({ 'background': 'transparent url(' + settings.imageBlank + ') no-repeat' }); }).show().bind('click', function() { settings.activeImage = settings.activeImage + 1; _set_image_to_view(); return false; }); } }
            _enable_keyboard_navigation();
        }
        function _enable_keyboard_navigation() { $(document).keydown(function(objEvent) { _keyboard_action(objEvent); }); }
        function _disable_keyboard_navigation() { $(document).unbind(); }
        function _keyboard_action(objEvent) {
            if (objEvent == null) { keycode = event.keyCode; escapeKey = 27; } else { keycode = objEvent.keyCode; escapeKey = objEvent.DOM_VK_ESCAPE; }
            key = String.fromCharCode(keycode).toLowerCase(); if ((key == settings.keyToClose) || (key == 'x') || (keycode == escapeKey)) { _finish(); }
            if ((key == settings.keyToPrev) || (keycode == 37)) { if (settings.activeImage != 0) { settings.activeImage = settings.activeImage - 1; _set_image_to_view(); _disable_keyboard_navigation(); } }
            if ((key == settings.keyToNext) || (keycode == 39)) { if (settings.activeImage != (settings.imageArray.length - 1)) { settings.activeImage = settings.activeImage + 1; _set_image_to_view(); _disable_keyboard_navigation(); } }
        }
        function _preload_neighbor_images() {
            if ((settings.imageArray.length - 1) > settings.activeImage) { objNext = new Image(); objNext.src = settings.imageArray[settings.activeImage + 1][0]; }
            if (settings.activeImage > 0) { objPrev = new Image(); objPrev.src = settings.imageArray[settings.activeImage - 1][0]; }
        }
        function _finish() { $('#jquery-lightbox').remove(); $('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); }); $('embed, object, select').css({ 'visibility': 'visible' }); }
        function ___getPageSize() {
            var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight) { xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; }
            var windowWidth, windowHeight; if (self.innerHeight) {
                if (document.documentElement.clientWidth) { windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; }
                windowHeight = self.innerHeight;
            } else if (document.documentElement && document.documentElement.clientHeight) { windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else if (document.body) { windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; }
            if (yScroll < windowHeight) { pageHeight = windowHeight; } else { pageHeight = yScroll; }
            if (xScroll < windowWidth) { pageWidth = xScroll; } else { pageWidth = windowWidth; }
            arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight); return arrayPageSize;


        }; function ___getPageScroll() {
            var xScroll, yScroll; if (self.pageYOffset) { yScroll = self.pageYOffset; xScroll = self.pageXOffset; } else if (document.documentElement && document.documentElement.scrollTop) { yScroll = document.documentElement.scrollTop; xScroll = document.documentElement.scrollLeft; } else if (document.body) { yScroll = document.body.scrollTop; xScroll = document.body.scrollLeft; }
            arrayPageScroll = new Array(xScroll, yScroll); return arrayPageScroll;
        }; function ___pause(ms) {
            var date = new Date(); curDate = null; do { var curDate = new Date(); }
            while (curDate - date < ms);
        }; return this.unbind('click').click(_initialize);
    };
})(jQuery);

/**
* Ajax upload
* Project page - http://valums.com/ajax-upload/
* Copyright (c) 2008 Andris Valums, http://valums.com
* Licensed under the MIT license (http://valums.com/mit-license/)
* Version 3.0 (05.04.2009)
*/

/**
* Changes from the previous version
* 1. Fixed Opera 9.64 response problem
* 2. Added responseType parameter
* 
* For the full changelog please visit: 
* http://valums.com/ajax-upload-changelog/
*/

(function() {

    var d = document, w = window;

    /**
    * Get element by id
    */
    function get(element) {
        if (typeof element == "string")
            element = d.getElementById(element);
        return element;
    }

    /**
    * Attaches event to a dom element
    */
    function addEvent(el, type, fn) {
        if (w.addEventListener) {
            el.addEventListener(type, fn, false);
        } else if (w.attachEvent) {
            var f = function() {
                fn.call(el, w.event);
            };
            el.attachEvent('on' + type, f)
        }
    }


    /**
    * Creates and returns element from html chunk
    */
    var toElement = function() {
        var div = d.createElement('div');
        return function(html) {
            div.innerHTML = html;
            var el = div.childNodes[0];
            div.removeChild(el);
            return el;
        }
    } ();

    function hasClass(ele, cls) {
        return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
    }
    function addClass(ele, cls) {
        if (!hasClass(ele, cls)) ele.className += " " + cls;
    }
    function removeClass(ele, cls) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        ele.className = ele.className.replace(reg, ' ');
    }

    // getOffset function copied from jQuery lib (http://jquery.com/)
    if (document.documentElement["getBoundingClientRect"]) {
        // Get Offset using getBoundingClientRect
        // http://ejohn.org/blog/getboundingclientrect-is-awesome/
        var getOffset = function(el) {
            var box = el.getBoundingClientRect(),
		doc = el.ownerDocument,
		body = doc.body,
		docElem = doc.documentElement,

            // for ie 
		clientTop = docElem.clientTop || body.clientTop || 0,
		clientLeft = docElem.clientLeft || body.clientLeft || 0,

            // In Internet Explorer 7 getBoundingClientRect property is treated as physical,
            // while others are logical. Make all logical, like in IE8.


		zoom = 1;
            if (body.getBoundingClientRect) {
                var bound = body.getBoundingClientRect();
                zoom = (bound.right - bound.left) / body.clientWidth;
            }
            if (zoom > 1) {
                clientTop = 0;
                clientLeft = 0;
            }
            var top = box.top / zoom + (window.pageYOffset || docElem && docElem.scrollTop / zoom || body.scrollTop / zoom) - clientTop,
		left = box.left / zoom + (window.pageXOffset || docElem && docElem.scrollLeft / zoom || body.scrollLeft / zoom) - clientLeft;

            return {
                top: top,
                left: left
            };
        }

    } else {
        // Get offset adding all offsets 
        var getOffset = function(el) {
            if (w.jQuery) {
                return jQuery(el).offset();
            }

            var top = 0, left = 0;
            do {
                top += el.offsetTop || 0;
                left += el.offsetLeft || 0;
            }
            while (el = el.offsetParent);

            return {
                left: left,
                top: top
            };
        }
    }

    function getBox(el) {
        var left, right, top, bottom;
        var offset = getOffset(el);
        left = offset.left;
        top = offset.top;

        right = left + el.offsetWidth;
        bottom = top + el.offsetHeight;

        return {
            left: left,
            right: right,
            top: top,
            bottom: bottom
        };
    }

    /**
    * Crossbrowser mouse coordinates
    */
    function getMouseCoords(e) {
        // pageX/Y is not supported in IE
        // http://www.quirksmode.org/dom/w3c_cssom.html			
        if (!e.pageX && e.clientX) {
            // In Internet Explorer 7 some properties (mouse coordinates) are treated as physical,
            // while others are logical (offset).
            var zoom = 1;
            var body = document.body;

            if (body.getBoundingClientRect) {
                var bound = body.getBoundingClientRect();
                zoom = (bound.right - bound.left) / body.clientWidth;
            }

            return {
                x: e.clientX / zoom + d.body.scrollLeft + d.documentElement.scrollLeft,
                y: e.clientY / zoom + d.body.scrollTop + d.documentElement.scrollTop
            };
        }

        return {
            x: e.pageX,
            y: e.pageY
        };

    }
    /**
    * Function generates unique id
    */
    var getUID = function() {
        var id = 0;
        return function() {
            return 'ValumsAjaxUpload' + id++;
        }
    } ();

    function fileFromPath(file) {
        return file.replace(/.*(\/|\\)/, "");
    }

    function getExt(file) {
        return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : '';
    }

    // Please use AjaxUpload , Ajax_upload will be removed in the next version
    Ajax_upload = AjaxUpload = function(button, options) {
        if (button.jquery) {
            // jquery object was passed
            button = button[0];
        } else if (typeof button == "string" && /^#.*/.test(button)) {
            button = button.slice(1);
        }
        button = get(button);

        this._input = null;
        this._button = button;
        this._disabled = false;
        this._submitting = false;

        this._settings = {
            // Location of the server-side upload script
            action: 'upload.php',
            // File upload name
            name: 'userfile',
            // Additional data to send
            data: {},
            // Submit file as soon as it's selected
            autoSubmit: true,
            // The type of data that you're expecting back from the server.
            // Html and xml are detected automatically.
            // Only useful when you are using json data as a response.
            // Set to "json" in that case. 
            responseType: false,
            // When user selects a file, useful with autoSubmit disabled			
            onChange: function(file, extension) { },
            // Callback to fire before file is uploaded
            // You can return false to cancel upload
            onSubmit: function(file, extension) { },
            // Fired when file upload is completed
            onComplete: function(file, response) { }
        };

        // Merge the users options with our defaults
        for (var i in options) {
            this._settings[i] = options[i];
        }

        this._createInput();
        this._rerouteClicks();
    }

    // assigning methods to our class
    AjaxUpload.prototype = {
        setData: function(data) {
            this._settings.data = data;
        },
        disable: function() {
            this._disabled = true;
        },
        enable: function() {
            this._disabled = false;
        },
        // use setData instead, set_data will be removed in the next version
        set_data: function(data) {
            this.setData(data);
        },
        // removes ajaxupload
        destroy: function() {
            if (this._input) {
                if (this._input.parentNode) {
                    this._input.parentNode.removeChild(this._input);
                }
                this._input = null;
            }
        },
        /**
        * Creates invisible file input above the button 
        */
        _createInput: function() {
            var self = this;
            var input = d.createElement("input");
            input.setAttribute('type', 'file');
            input.setAttribute('name', this._settings.name);
            var styles = {
                'position': 'absolute'
			, 'margin': '-5px 0 0 -175px'
			, 'padding': 0
			, 'width': '220px'
			, 'height': '10px'
			, 'opacity': 0
			, 'cursor': 'pointer'
			, 'display': 'none'
			, 'zIndex': 2147483583 //Max zIndex supported by Opera 9.0-9.2x 
                // Strange, I expected 2147483647					
            };
            for (var i in styles) {
                input.style[i] = styles[i];
            }

            // Make sure that element opacity exists
            // (IE uses filter instead)
            if (!(input.style.opacity === "0")) {
                input.style.filter = "alpha(opacity=0)";
            }
            d.body.appendChild(input);

            if (window.jQuery && jQuery.ui && jQuery.ui.dialog) {
                // make plugin compatible when using with ui-dialogs with modal = true
                jQuery(input)
				.wrap('<div></div>')
				.parent()
				.addClass('ui-dialog-ajaxupload')
				.css({
				    'zIndex': styles.zIndex
					, 'width': 0
					, 'height': 0
					, 'padding': 0
					, 'margin': 0
				});
            }

            addEvent(input, 'change', function() {
                // get filename from input
                var file = fileFromPath(this.value);
                if (self._settings.onChange.call(self, file, getExt(file)) == false) {
                    return;
                }
                // Submit form when value is changed
                if (self._settings.autoSubmit) {
                    self.submit();
                }
            });

            this._input = input;
        },
        _rerouteClicks: function() {
            var self = this;

            // IE displays 'access denied' error when using this method
            // other browsers just ignore click()
            // addEvent(this._button, 'click', function(e){
            //   self._input.click();
            // });				

            var box, over = false;
            addEvent(self._button, 'mouseover', function(e) {
                if (!self._input || over) return;
                over = true;
                box = getBox(self._button);

            });

            // we can't use mouseout on the button,
            // because invisible input is over it
            addEvent(document, 'mousemove', function(e) {
                var input = self._input;
                if (!input || !over) return;
                if (self._disabled) {
                    removeClass(self._button, 'hover');
                    input.style.display = 'none';
                    return;
                }

                var c = getMouseCoords(e);

                if ((c.x >= box.left) && (c.x <= box.right) &&
			(c.y >= box.top) && (c.y <= box.bottom)) {

                    input.style.top = c.y + 'px';
                    input.style.left = c.x + 'px';
                    input.style.display = 'block';
                    addClass(self._button, 'hover');
                } else {
                    // mouse left the button
                    over = false;
                    input.style.display = 'none';
                    removeClass(self._button, 'hover');
                }
            });

        },
        /**
        * Creates iframe with unique name
        */
        _createIframe: function() {
            // unique name
            // We cannot use getTime, because it sometimes return
            // same value in safari :(
            var id = getUID();

            // Remove ie6 "This page contains both secure and nonsecure items" prompt 
            // http://tinyurl.com/77w9wh
            var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
            iframe.id = id;
            iframe.style.display = 'none';
            d.body.appendChild(iframe);
            return iframe;
        },
        /**
        * Upload file without refreshing the page
        */
        submit: function() {
            var self = this, settings = this._settings;

            if (this._input.value === '') {
                // there is no file
                return;
            }

            // get filename from input
            var file = fileFromPath(this._input.value);

            // execute user event
            if (!(settings.onSubmit.call(this, file, getExt(file)) == false)) {
                // Create new iframe for this submission
                var iframe = this._createIframe();

                // Do not submit if user function returns false										
                var form = this._createForm(iframe);
                form.appendChild(this._input);

                form.submit();

                d.body.removeChild(form);
                form = null;
                this._input = null;

                // create new input
                this._createInput();

                var toDeleteFlag = false;
                var fired = false;

                addEvent(iframe, 'load', function(e) {
                    if (iframe.src == "about:blank") {
                        // First time around, do not delete.
                        if (toDeleteFlag) {
                            // Fix busy state in FF3
                            setTimeout(function() {
                                d.body.removeChild(iframe);
                            }, 0);
                        }
                        return;
                    }

                    if (fired) {
                        // Event was already fired
                        // fixing Opera 9.64 that do it multiple times
                        return;
                    }

                    var doc = iframe.contentDocument ? iframe.contentDocument : frames[iframe.id].document;

                    // fixing Opera 9.26
                    if (doc.readyState && doc.readyState != 'complete') {
                        // Opera fires load event multiple times
                        // Even when the DOM is not ready yet
                        // this fix should not affect other browsers
                        return;
                    }

                    // fixing Opera 9.64
                    fired = true;

                    if (doc.body && doc.body.innerHTML == "false") {
                        // In Opera 9.64 event was fired second time
                        // when body.innerHTML changed from false 
                        // to server response approx. after 1 sec					
                        window.setTimeout(function() {
                            onLoad();
                        }, 4321);
                    } else {
                        onLoad();
                    }

                    function onLoad() {
                        var response;

                        if (doc.XMLDocument) {
                            // response is a xml document IE property
                            response = doc.XMLDocument;
                        } else if (doc.body) {
                            // response is html document or plain text
                            response = doc.body.innerHTML;
                            if (settings.responseType == 'json') {
                                response = window["eval"]("(" + response + ")");
                            }
                        } else {
                            // response is a xml document
                            var response = doc;
                        }

                        settings.onComplete.call(self, file, response);

                        // Reload blank page, so that reloading main page
                        // does not re-submit the post. Also, remember to
                        // delete the frame
                        toDeleteFlag = true;
                        iframe.src = "about:blank"; //load event fired	
                    }
                });

            } else {
                // clear input to allow user to select same file
                this._input.value = '';
            }
        },
        /**
        * Creates form, that will be submitted to iframe
        */
        _createForm: function(iframe) {
            var settings = this._settings;

            // method, enctype must be specified here
            // because changing this attr on the fly is not allowed in IE 6/7		
            var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
            form.style.display = 'none';
            form.action = settings.action;
            form.target = iframe.name;
            d.body.appendChild(form);

            // Create hidden input element for each data key
            for (var prop in settings.data) {
                var el = d.createElement("input");
                el.type = 'hidden';
                el.name = prop;
                el.value = settings.data[prop];
                form.appendChild(el);
            }
            return form;
        }
    };
})();