/*************************************
 *
 *  Code By Attenzione
 *  Started at 21.04.2008
 *
 *************************************/

var iw = new Object();

iw.functions = {

	getAjaxBody : function( responseText ) {
		var bodyStart = responseText.toLowerCase().indexOf("<body>");
		var bodyEnd = responseText.toLowerCase().indexOf("</body>");

		if (bodyStart > -1 && bodyEnd > -1)	{
			responseText = responseText.substring( bodyStart + 6, bodyEnd );
		}
		return responseText;
	},

	scrollToName: function( name, offset ) {
		var o = $('[name='+name+']');
		if (!o.length) return false;
		if (typeof offset == 'undefined') offset = 0;
		window.scroll( 0, o.offset().top - offset );
	}

};

iw.viewport = {
	windowX : function() { return (document.documentElement && document.documentElement.clientWidth) || window.innerWidth || self.innerWidth || document.body.clientWidth },
	windowY : function() { return (document.documentElement && document.documentElement.clientHeight) || window.innerHeight || self.innerHeight || document.body.clientHeight },
	scrollX : function() { return (document.documentElement && document.documentElement.scrollLeft) || window.pageXOffset || self.pageXOffset || document.body.scrollLeft },
	scrollY : function() { return (document.documentElement && document.documentElement.scrollTop) || window.pageYOffset || self.pageYOffset || document.body.scrollTop },
	pageX 	: function() { return (document.documentElement && document.documentElement.scrollWidth) ? document.documentElement.scrollWidth : (document.body.scrollWidth > document.body.offsetWidth) ? document.body.scrollWidth : document.body.offsetWidth },
	pageY 	: function() { return (document.documentElement && document.documentElement.scrollHeight) ? document.documentElement.scrollHeight : (document.body.scrollHeight > document.body.offsetHeight) ? document.body.scrollHeight : document.body.offsetHeight }
}

iw.preloader = {
	o : null,
	p : null,
	show : function( selector ) {
		if (!this.init( selector )) return false;
		this.p.removeClass('preloader-instance').prependTo( this.o ).show();
		return true;
	},
	hide : function( selector ) {
		if (!this.init( selector )) return false;
		this.o.find('div.preloader').remove();
		return true;
	},
	init : function( selector ) {
		var o = $( selector );
		if (!o.length) return false;
		this.o = o;
		//var p = $('div.preloader-instance');
		//if (!p.length) return false;
		var msg = typeof settings.preloader != 'undefined' ? settings.preloader : '';
		this.p = $('<div class="preloader"><div><span>'+msg+'</span></div><div class="preloader-overlay"></div></div>');
		var height = this.o.height();
		var padding = height < 600 ? Math.max(0, Math.round( height / 2 ) - 15) : 250;
		this.p.find('div').css({
			'padding-top' : padding,
			'height' : height - padding
		});
		return true;
	}
}

function _$( id ) {
	return document.getElementById( id );
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.onlyLatinChars = function() {

	var chars = {
		'ā' : 'a',
		'ē' : 'e',
		'ī' : 'i',
		'ū' : 'u',
		'õ' : 'o',
		'ŗ' : 'r',
		'š' : 's',
		'ģ' : 'g',
		'ķ' : 'k',
		'ļ' : 'l',
		'ž' : 'z',
		'č' : 'c',
		'ņ' : 'n'
	};
	var str = this;
	var r = new RegExp();
	for ( i in chars ) {
		r = new RegExp( i, 'g' );
		str = str.replace( r, chars[i] );
		r = new RegExp( i.toUpperCase(), 'g' );
		str = str.replace( r, chars[i].toUpperCase() );
	}
	return str;

}

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/number/fmt-money [rev. #2]
Number.prototype.currency = function(c, d, t) {
    var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "",
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t)
    + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

function in_array(myValue,myArray) {
    function equals(a,b) {
        return (a == b);
    }

    for (var i in myArray) {
        if (equals(myArray[i],myValue))
            return true;
    }

    return false;
}

function _noBubbling( e ) {
	e = _fixE( e );
	if (!e.cancelBubble) e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
    return false;
}

function _fixE( e ) {
	if (!e) e = window.event;
	return e;
}

// Get user selection text on page
function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection();
    }
    else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}
function getSelectionPositions( element ) {
	if( document.selection ){
		// The current selection
		var range = document.selection.createRange();
		// We'll use this as a 'dummy'
		var stored_range = range.duplicate();
		// Select all text
		stored_range.moveToElementText( element );
		// Now move 'dummy' end point to end point of original range
		stored_range.setEndPoint( 'EndToEnd', range );
		// Now we can calculate start and end points
		element.selectionStart = stored_range.text.length - range.text.length;
		element.selectionEnd = element.selectionStart + range.text.length;
	}
	return { start: element.selectionStart, end: element.selectionEnd };
}
function setSelectionPositions( element, start, end ) {

	if (!end || typeof end == 'undefined') end = start;
	// IE Support
	if (document.selection) {

		// Set focus on the element
		element.focus ();

		// Create empty selection range
		var oSel = document.selection.createRange ();

		// Move selection start and end to 0 position
		//oSel.moveStart ('character', -element.value.length);

		// Move selection start and end to desired position
		oSel.moveStart ('character', start);
		oSel.moveEnd ('character', -element.value.length + end);
		oSel.select ();

	} else if (element.selectionStart || element.selectionStart == '0') {

		element.focus ();
		element.selectionStart = start;
		element.selectionEnd = end;


	}

}

function m( n, d, s ) {

	n = n.split(',');
	var nn = '';
	for (var i = 0; i < n.length; i++) {
		nn += String.fromCharCode(n[i]);
	}
	d = d.split(',');
	var dd = '';
	for (var i = 0; i < d.length; i++) {
		dd += String.fromCharCode(d[i]);
	}
	if (s) {
		s = s.split(',');
		var ss = '';
		for (var i = 0; i < s.length; i++) {
			ss += String.fromCharCode(s[i]);
		}
	}

	var l = '';
	l += String.fromCharCode(109);
	l += String.fromCharCode(97);
	l += String.fromCharCode(105);
	l += String.fromCharCode(108);
	l += String.fromCharCode(116);
	l += String.fromCharCode(111);
	l += String.fromCharCode(58);
	l += nn;
	l += String.fromCharCode(64);
	l += dd;
	if (ss) {
		l += String.fromCharCode(63);
		l += String.fromCharCode(115);
		l += String.fromCharCode(117);
		l += String.fromCharCode(98);
		l += String.fromCharCode(106);
		l += String.fromCharCode(101);
		l += String.fromCharCode(99);
		l += String.fromCharCode(116);
		l += String.fromCharCode(61);
		l += ss;
	}
	window.location = l;
	return false;
}

function formSubmit( actionObj, preloader ) {

	var callerObj;
	callerObj = actionObj = $( actionObj );
	if (callerObj.attr('__iw_busy')) return false;
	callerObj.attr('__iw_busy', true);

	if ( actionObj.get(0).tagName.toLowerCase() == 'form') {
		var parentForm = actionObj;
	} else {
		if (actionObj.get(0).tagName.toLowerCase() == 'a') {
			actionObj.get(0).blur();
		}
		var parentForm = actionObj.parents('form:first');
	}

	var url = parentForm.get(0).action;
	if (!url) url = document.location.href;

	var options = {
		beforeSubmit: function() {
			document.body.style.cursor = 'wait';
			if (typeof preloader != 'undefined') {
				iw.preloader.show( preloader );
			}
		},
		url : url,
		type: "POST",
		complete: function() {
			document.body.style.cursor = 'default';
			if (typeof preloader != 'undefined') {
				iw.preloader.hide( preloader );
			}
			callerObj.removeAttr('__iw_busy');
		},
		success: function( responseText, statusText ) {

			document.body.style.cursor = 'default';
            responseText = iw.functions.getAjaxBody(responseText);
			evalScriptsOnResponse( responseText );

		}
	};
	parentForm.ajaxSubmit( options );

	return false;

}

function setAction( action, preloader ) {

	if (typeof action == 'object' && action.tagName.toLowerCase() == 'a') {
		action.blur();
		var actionObj = action;
		action = action.href;
	}
    var url = action;

	var options = {
		beforeSend: function() {
			document.body.style.cursor = 'wait';
			if (typeof preloader != 'undefined') {
				iw.preloader.show( preloader );
			}
		},
		url : url,
		type  : "GET",
		dataType: "text",
		complete: function() {
			document.body.style.cursor = 'default';
			if (typeof preloader != 'undefined') {
				iw.preloader.hide( preloader );
			}
		},
		success: function( responseText, statusText ) {

            responseText = iw.functions.getAjaxBody(responseText);
			evalScriptsOnResponse( responseText );

		}
	};
	$.ajax( options );
	return false;

}

function evalScriptsOnResponse( text ) {

	var scriptIndex = 0;
	var IWScripts = new Array();
	document.onIWRun = null;
	document.IWLoaded = true;

	/* It's Toooooo LONG! */
	/*aObj.find("script").each( function() {
		document.onIWComplete = null;
		eval( this.innerHTML );
		if (document.onIWComplete) {
			IWScripts[scriptIndex] = document.onIWComplete;
			scriptIndex++;
		}
	});*/

	/* remove all scripts */
	text = text.replace(/<(\/?)script/gi, "<$1script");
	var scriptStart = text.indexOf("<script");
	var scriptEnd = -1;
	var scriptBody = "";

	while(scriptStart > -1) {
		scriptEnd = text.indexOf("</script>")+9;
		scriptBody = text.substring(text.indexOf(">", scriptStart)+1, scriptEnd - 9);

		//reset collection function
		document.onIWComplete = null;
		try {
			eval( scriptBody );
		} catch (e) {
            if (typeof window.console != 'undefined' && typeof window.console.log != 'undefined') {
                window.console.log( e );
            }
		}
		if (document.onIWComplete) {
			IWScripts[scriptIndex] = document.onIWComplete;
			scriptIndex++;
		}

		//new html without executed script;
		text = text.substring(0,scriptStart)+text.substring(scriptEnd, text.length);
		scriptStart = text.indexOf("<script");
	}

	if (typeof document.onIWRun == 'function') {
		document.onIWRun( text );
	}

	if (IWScripts.length) {
		for (var i = 0; i < IWScripts.length; i++) {
			try {
				IWScripts[i]( );
			} catch (e) {
				window.console.log( e );
			}
		}
	}

}

var floatLayerID = 1000;
function floatContent( content, params ) {
	floatLayerID++;
	var zIndex = (floatLayerID - 999) * 3 + 100;
	var html =	'<div id="float-layer-bg-'+floatLayerID+'" class="float-layer-bg" style="display:none;z-index:'+zIndex+';"></div>'+
				'<div id="float-layer-'+floatLayerID+'" class="float-layer" style="display:none;z-index:'+(zIndex+1)+';">'+
					'<table class="float-layer">'+
						'<tr>'+
							'<td class="float-layer-inner">'+
								content +
							'</td>'+
						'</tr>'+
					'</table>'+
				'</div>';
	//attachSubmit( 'float-layer-inner' );
	$('body').prepend( html );
	showFloatLayer( floatLayerID, params );
}

function showFloatLayer( ID, params ) {

	var $floatLayer = $('#float-layer-' + ID);
	var $floatLayerPositioner = $('table.float-layer', $floatLayer);

	if (typeof params != 'undefined') {
		if (params.top) {
			if (params.top != 'window') {
				$floatLayerPositioner.find('td.float-layer-inner').css({'vertical-align' : 'top'});
				$floatLayerPositioner.css({'margin-top' : params.top, 'height' : 'auto'});
			}
		} else {
			$floatLayer.css('top', iw.viewport.scrollY());
		}
		if ( (params.left && params.left == 'click') || (params.right && params.right == 'click') ) {
			if ( typeof __iw_click.x != 'undefined' ) {
				var procL = parseInt( __iw_click.x / iw.viewport.pageX() * 100 );
				var procR = parseInt( (iw.viewport.pageX() - __iw_click.x ) / iw.viewport.pageX() * 100 );
				if (procL <= procR && procL < 30) {
					$floatLayerPositioner.css({'margin-left' : procL+'%'});
				} else if (procR < 30) {
					$floatLayerPositioner.css({'margin-right' : procR+'%'});
				}
			}
		} else if ( params.left ) {
			$floatLayerPositioner.css({'margin-left' : params.left, 'width' : 'auto'});
		} else if ( params.right ) {
			$floatLayerPositioner.css({'margin-right' : params.right, 'width' : 'auto'});
		}
		if ( params.width ) {
			$floatLayerPositioner.css({'width' : params.width});
		}
	} else {
		$floatLayer.css('top', iw.viewport.scrollY())
	}
	showColorLayer( ID );
	$floatLayer.show();
	//$(window).unbind('click', hideFloatLayer );
	//$(window).bind('click', hideFloatLayer );
}
function showColorLayer( ID ) { $('#float-layer-bg-'+ID).show(); }
function hideColorLayer( ID ) { $('#float-layer-bg-'+ID).remove(); }
function hideFloatLayer( ) {
	while (floatLayerID > 1000) {
		var l = $('#float-layer-'+floatLayerID);
		if (l.length) {
			l.remove();
			hideColorLayer( floatLayerID );
			floatLayerID--;
			break;
		}
		floatLayerID--;
	}
}
function resizeFloatLayer() {
	return false;
	var contentHeight = $('#float-layer-inner').height();
	var top = Math.abs(Math.round((viewport.windowY() - contentHeight) / 2));
	top += view.scrollY;
	$('#float-layer').css('top', top);
}

function refreshPage( url ) {
    if (typeof url == 'undefined' || !url) {
        window.location.reload(true);
    } else {
        window.location.href = url;
    }
}

function pageRefresh( url ) {
	refreshPage ( url );
}

function switchImage( target, src, oncomplete ) {

	var im = new Image();
	target = $(target);
	//iw.preloader.show( target.parent() );
	im.onload = function() {
		var img = target.find('img');
		if (target.length && img.length) {
			var targetDOM = target.get(0);
			var imgDOM = img.get(0);
			var width = im.width;
			var height = im.height;
			targetDOM.style.width = imgDOM.width + 'px';
			targetDOM.style.height = imgDOM.height + 'px';
			target.css('overflow', 'hidden');
			if ($.browser.msie) {
				target.css({'width': width, 'height': height});
				//imgDOM.src = src;
				img.attr({
				    "src": src,
				    "width": width,
				    "height": height
				});

				if (typeof oncomplete == 'function') { oncomplete(); }
			} else {
				target.animate({'opacity': 0}, 200, false, function() {
					$(this).animate({'width': width, 'height': height}, 300, false, function() {
						//imgDOM.src = src;
						img.attr({
						    "src": src,
						    "width": width,
						    "height": height
						});
						$(this).animate({'opacity': 1}, 200, false, function() {
							if (typeof oncomplete == 'function') { oncomplete(); }
						});
					});
				});
			}
		}
	}
	im.src = src;

}

function checkFirebug() {
	return (typeof window.console == 'object' && typeof window.console.firebug != 'undefined');
}

/*########################################*/

function recaptcha( _this ) {
	var dt = new Date();
	var im = $(_this).find('img.captcha');
	im.attr('src', im.attr('src').replace(/\?(.*)$/, '?'+dt.getTime() ));
	return false;
}

