if(typeof(console) == 'undefined') console = {
	'log':function(a){ /*alert(a);*/ }
};

(function()
{
    /*  Custom window.ready method based on jQuery
     *  ready.js
     */

    if(typeof(window.ready)=='undefined')
    {
    	var readyInitCallOnce = false;
    	function readyInit()
    	{
    		if(readyInitCallOnce) return;
    		readyInitCallOnce = true;
    		window.calls = [];
    
    		// Mozilla, Opera and webkit nightlies currently support this event
    		if ( document.addEventListener ) {
    			// Use the handy event callback
    			document.addEventListener( "DOMContentLoaded", function(){
    				document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
    				//jQuery.ready();
    				call();
    			}, false );
    
    		// If IE event model is used
    		} else if ( document.attachEvent ) {
    			// ensure firing before onload,
    			// maybe late but safe also for iframes
    			document.attachEvent("onreadystatechange", function(){
    				if ( document.readyState === "complete" ) {
    					document.detachEvent( "onreadystatechange", arguments.callee );
    					//jQuery.ready();
    					call();
    				}
    			});
    
    			// If IE and not an iframe
    			// continually check to see if the document is ready
    			if ( document.documentElement.doScroll && window == window.top ) (function(){
    				//if ( jQuery.isReady ) return;
    				if(typeof(window.trovit_loaded)!='undefined') return;
    
    				try {
    					// If IE is used, use the trick by Diego Perini
    					// http://javascript.nwbox.com/IEContentLoaded/
    					document.documentElement.doScroll("left");
    				} catch( error ) {
    					setTimeout( arguments.callee, 0 );
    					return;
    				}
    
    				// and execute any waiting functions
    				//jQuery.ready();
    				call();
    			})();
    		}
    
    		// A fallback to window.onload, that will always work
    		//jQuery.event.add( window, "load", /*jQuery.ready*/ ready );
    		//window.load = call;
    	}
    	
    	function call()
    	{
    		if(typeof(window.trovit_loaded)=='undefined' || !!window.trovit_loaded==false){
    			window.trovit_loaded = true;
    			for(var i=0; i<window.calls.length; i++){
                    window.calls[i]();
                }
            }
    	}
    	
    	window.ready = function( fn)
    	{
    		readyInit();
    		window.calls.push(fn);
    	}
    }
    
    /* Trovit ads
     * Global params
     */
    
    trovit_ads  = typeof(trovit_ads) != 'object'? trovit_show_ads():trovit_ads;
	trovit_vars = typeof(trovit_vars)=='undefined'?
    {
		'trovit_id'				: 'id',		// hash del publisher
		'trovit_ad_id'          : 'aid',    // id del anuncio
		'trovit_query'			: 'q',		// query para buscar anuncios
		'trovit_type'			: 't',		// tipo (si es homes)
		'trovit_v_name'			: 'v',		// vertical (homes cars o jobs; o hc, hj o cj
		'trovit_c_name'			: 'c',		// país
		//'trovit_ch'        	: 'ch',     // canal
		'trovit_ch_name'        : 'ch',     // canal
		'trovit_n_ads'			: 'n',		// numero de anuncios
		'trovit_width'			: 'w',		// width
		'trovit_height'			: 'h',		// height
		'trovit_format'			: 'f',		// format
		'trovit_domain'         : 'd',      // custom domain
		
        'trovit_color_text'     : 'cc',
        'trovit_color_link'     : 'lc',
        'trovit_color_background':'bc',
        'trovit_color_title'    : 'tc',
		'trovit_color_border'   : 'oc',
		
		'trovit_font_family'    : 'ff',
		'trovit_font_size'      : 'fs',

        'trovit_internal'       : 'ti',
		'trovit_ip'             : 'ip',
		'trovit_publishers_test': 'pt'
	}:trovit_vars;

	// create canvas & fill ops by ad
	(function()
    {
		var args = {'divid':'trovit_ads'+(trovit_ads.length+1)};
		for(var k in trovit_vars){
			try { eval("args."+k+" = "+k+"; "+k+" = null;"); }
			catch(e){ args[k] = null; }
		}

		if(args.trovit_internal != true) {
			document.write('<div id="'+args.divid+'"></div>');
		}
        trovit_ads.length += 1;
        
        if(args.trovit_internal==true){ trovit_ads.fillAd(args); }
        else window.ready(function(){ trovit_ads.fillAd(args); });
	})();
    
    
    /* Trovit Ads Class: create prototype & instance new trovit_ads;
     * trovit_ads.js
     */

	function trovit_show_ads()
	{
		// main trovit_ads object
		trovit_ads = function(){}
        
        // number of ads
        trovit_ads.prototype.length = 0;
		
		// ip
		trovit_ads.prototype.ip = null;
		
		// test prefix
        trovit_ads.prototype.sfx = window.location.hostname.search('preprod')!=-1?'.preprod':'';
        	
		// prototype implementation class
		trovit_ads.prototype.fillAd = function( ops)
		{			
            var ran = this.rand(10000,90000);
            
			var src = 'http://premium.trovit.com'+(trovit_ads.sfx)+'/src/show_ads.php?rand='+ran+'&divid='+ops.divid+'&';
			var div = document.getElementById(ops.divid);
			for(k in trovit_vars) if(ops[k]!=null) src += (trovit_vars[k])+'='+encodeURIComponent(ops[k])+'&';
			
			if (ops.trovit_internal != null) {
				document.write('<script type="text/javascript" src="' + src + '" charset="UTF-8"><\/script>');
			}
            else
			{
                var writeIframe = function(){
                    if (trovit_ads.ip == null) {
                        trovit_ads.ip = ip;
					}
					src += '&ip='+trovit_ads.ip;

                    // add source url origin
                    if (ops.trovit_format == 'search') {
					   src += '&tus=' + encodeURIComponent(document.location.href);
					   var trovitanchor = trovit_ads.getTrovitSearchAnchor();
					   if(trovitanchor!=''){
					       src = 'http://custom.trovit.com'+(trovit_ads.sfx)+'?'+trovitanchor;
					   }
					}

					div.innerHTML = '<iframe width="'+ops.trovit_width+'" name="trovit_ads" src="" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" frameborder="0" scrolling="no">fail</iframe>';
                    var ifr = div.getElementsByTagName('iframe')[0]; ifr.src = src;
                    trovit_ads.frameHeight(ops,ifr);
                }
				
				if (trovit_ads.ip == null) {
					var jsip = 'http://premium.trovit.com'+(trovit_ads.sfx)+'/src/getip.php';
					trovit_ads.loadjs(jsip, writeIframe);
				}
				else {
					writeIframe();
				}
			}
        }
		
		trovit_ads.prototype.getTrovitSearchAnchor = function()
		{
			if(document.location.href.search('#trovit_search:')!=-1) return document.location.href.split('#trovit_search:')[1];
			else return '';
		}
		
		trovit_ads.prototype.frameHeight = function( ops, f)
		{
			var height = '';

            // fixed height
			if(ops.trovit_height != null) {
				height = ops.trovit_height;
				f.height = parseInt(height);
			}
			
			if(ops.trovit_format == 'search')
			{
	            var ifrload = function()
				{
                    var hash = trovit_ads.getTrovitSearchAnchor();
					if(hash!='' && hash.search('&ifh=')!=-1){
						height = hash.split('&ifh=')[1];
					}
					
	                if (height != '') {
	                    f.style.height = this.height = parseInt(height);
					}
	                window.scrollTo(0, 0);
				};
	            f.attachEvent?f.attachEvent("onload",ifrload):f.addEventListener("load",ifrload,false);
            }	
		}
		
		trovit_ads.prototype.loadjs = function( f, call)
		{
			var script = document.createElement('script');
			script.type = 'text/javascript';
			script.src = f;
			
			// Alert when the script is loaded
			if (typeof(script.onreadystatechange) == 'undefined') // W3C
			script.onload = function(){ this.onload = null; call(); };
			else // IE
			script.onreadystatechange = function(){ if (this.readyState != 'loaded' && this.readyState != 'complete') return; this.onreadystatechange = null; call(); };
			
			// Add script DOM element to document tree
			document.getElementsByTagName('head')[0].appendChild(script);
		}
		
		trovit_ads.prototype.trim = function( str)
		{
			return str.replace(/^\s+|\s+$/g,'');
		}

        trovit_ads.prototype.rand = function( min, max)
        {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }

	    return new trovit_ads();
	};

})();
