var included_files = new Array();

function include_once(script_filename) {
    if (!in_array(script_filename, included_files)) {
        included_files[included_files.length] = script_filename;
        include_dom(script_filename);  // canviar per include_dom??
        //alert("Carregat el fitxer " + script_filename);
    }
}

function include_dom(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    
    //var oNew = document.createElement("script");
    //oNew.type = "text/javascript";
    //oNew.src = script_filename;
    //hIncludes[script_filename]=true;
    //document.getElementsByTagName("head")[0].appendChild(oNew);

    html_doc.appendChild(js);
    return false;
}

function in_array(needle, haystack) {
    for (var i = 0; i < haystack.length; i++) {
        if (haystack[i] == needle) {
            return true;
        }
    }
    return false;
}

function afegeix_estils(fitxer) {
	//if (!in_array(fitxer, included_files)) {
        included_files[included_files.length] = fitxer;
        $("head").append("<link>");
        css = $("head").children(":last");
        css.attr({
          rel:  "stylesheet",
          type: "text/css",
          href: fitxer
        });
    //}	
	return false;
}

function flash() {
	document.write('<!--[if IE]>\n');
	document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="100%" height="100%" align="l">\n');
	document.write('<param name="movie" value="media/fons_ok.swf" align="left" />\n');
	document.write('<param name="quality" value="high" />\n');
	document.write('<param name="scale" value="exactfit" />\n');
	document.write('<param name="wmode" value="transparent" />\n');
	document.write('</object>\n');
	document.write('<![endif]-->\n');
	document.write('<!--[if !IE]>-->\n');
	document.write('<object data="media/fons_ok.swf" width="100%" height="100%" type="application/x-shockwave-flash" align="l">\n');
	document.write('<param name="quality" value="high" />\n');
	document.write('<param name="wmode" value="transparent" />\n');
	document.write('<param name="pluginurl" value="http://www.macromedia.com/go/getflashplayer" />\n');
	document.write('<param name="scale" value="exactfit" />\n');
	document.write('FAIL (the browser should render some flash content, not this).\n');
	document.write('</object>\n');
	document.write('<!--<![endif]-->\n');
}

var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");

function fixPng(png) {
	   // get src
	   var src = png.src;
	   // set width and height
	   if (!png.style.width) { png.style.width = $(png).width(); }
	   if (!png.style.height) { png.style.height = $(png).height(); }
	   // replace by blank image
	   png.onload = function() { };
	   png.src = blank.src;
	   // set filter (display original image)
	   png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
 }

function roll(elem,imag,ext,ruta){
	if (ext == null){
   ext = 'gif';
   ruta= 'img/menu/';
 	}
	document.getElementById(elem).src=ruta+imag+'.'+ext;
	if(ext='png'){
	 	if (badBrowser) {
    	fixPng(document.getElementById(elem));
		}
	}
}

function roll_fons(elem, color){
	$('#' + elem).css({backgroundColor:"#" + color});
}


// manera correcta de passar funcions a jQuery i cridar a la funció: posar-li el nom de la variable sense ()
var canvianoti = function () {
	$.ajax({
		type: "GET",
		// Atenció: amb el mod_rewrite activat, passar-li sempre [QSA] al final de la línia
		// (veure http://stackoverflow.com/questions/1969646/jquery-ajax-htaccess)
		url: this.href,
		data: "action=cambianoti",
		error: function(msg){
			alert('Error de AJAX');
		},
		success: function(msg){
			$('div#wrapnoti').html(msg);	
		}
	});
	return false;
};

jQuery.preloadImages = function(){
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
};

function roll_fons_img(laid, imag, ruta){
			if (ruta == null){
		   ruta= 'img/';
		 	}
			$('#' + laid).css({'background-image': 'url("' + ruta + imag + '")'});
}

var blank = new Image();
blank.src = 'img/blank.gif';

// Increïble... si fem açò amb un append del jQuery, en IE no se sent la música!! (serà qüestió de les URL??)
function flash2() {
	document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="30" height="45" id="player" align="middle">\n');
	document.write('<param name="allowScriptAccess" value="sameDomain" />\n');
	document.write('<param name="movie" value="reproductor.swf" />\n');
	document.write('<param name="quality" value="high" />\n');
	document.write('<param name="bgcolor" value="#000000" />\n');
	document.write('<embed src="reproductor.swf" quality="high" bgcolor="#000000" width="30" height="45" name="player" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />\n');
	document.write('</object>\n');
}

$.extend({
	  getUrlVars: function(par){
	    var vars = [], hash;
	    var hashes = par.slice(par.indexOf('?') + 1).split('&');
	    for(var i = 0; i < hashes.length; i++)
	    {
	      hash = hashes[i].split('=');
	      vars.push(hash[0]);
	      vars[hash[0]] = hash[1];
	    }
	    return vars;
	  },
	  getUrlVar: function(par, name){
	    return $.getUrlVars(par)[name];
	  }
	});


function include(script_filename) {
  document.write(script_filename);
}

function restaura() {
	$('div.noti.formi textarea').val('Introduce aquí tu consulta:');
	$('div.noti.formi textarea').text('Introduce aquí tu consulta:');
	$('div#preformi input#nom').val('Introduce aquí tu nombre');
	$('div#preformi input#adreca').val('Introduce aquí tu dirección de correo electrónico');
	$('div#preformi input#telefon').val('Introduce aquí tu teléfono');
	return false;
}


//include_once('js/jquery/jquery.cycle.all.pack.js');

$(document).ready(function() { // Càgate lorito: si ho pose abans que ací, en IE 6 no va!

	  if (badBrowser) {
	    // get all pngs on page
	    $('img[src$=.png]').each(function() {
	      if (!this.complete) {
	        this.onload = function() { fixPng(this); };
	      } else {
	        fixPng(this);
	      }
	    });
	  }
	
		function redimensiona () {
				if($(window).height() > $('body').height()) {
					altura = $(window).height();
				}
				//else if($(document).height() > $('body').height()) {			
				//	altura = $(document).height();
				//}
				else {
					altura = $('body').height();
				}
				$('#fons').css({'height':altura + 'px'});
				//alert($(document).height());
				//alert($('body').height());
				//alert($(window).height());
		}
			
		redimensiona();
			
		$(window).bind('resize', function() {
			redimensiona();
		});
	
	//include_once("js/jquery/jquery.cycle.all.pack.js");
	//$('#fotos').cycle('fade');
		
	$('.boto_index').live("click", function () {
		include_once("js/jquery/jquery.cycle.all.pack.js");
		// $("title").text("Tutuning - Homologaciones :: Fichas reducidas :: Reformas de vehículos - Inicio");
		document.title = 'Tutuning - Homologaciones :: Fichas reducidas :: Reformas de vehículos - Inicio';
		$("#franja_central").load("index.php #franja_central", {}, function () {		
			$('#fotos').cycle('fade');
			return false;
		});
		$("#botonera").load("index.php #botonera");
		$("#continme div#inicio").html("");
		return false;
	});
	
	$('#boto_quienes').live("click", function () { // carreguem el "quienes somos"
	
		//$("title").text("Tutuning - Homologaciones :: Fichas reducidas :: Reformas de vehículos - Quienes somos"); // Açò provocarà error en IE
		document.title = 'Tutuning - Homologaciones :: Fichas reducidas :: Reformas de vehículos - Quienes somos'; 
		$("#continme div#inicio").load("quienes.php div#continme div#inicio", {}, function () {});
		$("#franja_central").load("quienes.php #franja_central");
		$("#botonera").load("quienes.php #botonera");	
		
		return false;
	});
	
	$('#boto_noti, #mesnotic, #boto_mesnoti').live("click", function () {
		
		include_once('js/jquery/jquery.mousewheel.min.js');
		include_once('js/jquery/jquery.em.js');
		include_once('js/jquery/jScrollPane.js');
		afegeix_estils("js/jquery/jScrollPane.css");
			
		
		/*
		 * Parafernàlia necessària pel mod_rewrite per a les notícies:
		 * Per a que clicant en "ver completa" de l'índex ens duga -via ajax- a la pàgina d'eixa notícia
		 * (i no a la llistà genèrica de notícies), hem de detectar el paràmetre ID de la notícia en la URL reescrita.
		 * Per a això hem de detectar si hem clicat en el botó de la secció "noticias", en "ver completa" de l'índex
		 * o en "ver completa" de "noticias"
		 */
		
		var trossos = this.href.split('/');
		var laidnoti; // aquesta
		
		if(trossos[trossos.length-1]!="noticias.php"){
			laidnoti = trossos[trossos.length-2];
		}
		else {
			laidnoti = $.getUrlVar(this.href, 'idnoti'); // i aquesta
		}
		    						
		//$("title").text("Tutuning - Homologaciones :: Fichas reducidas :: Reformas de vehículos - Noticias");
		document.title = 'Tutuning - Homologaciones :: Fichas reducidas :: Reformas de vehículos - Noticias';
		//$("#botonera").load("quienes.php #botonera");
		$("#continme div#inicio").load("noticias.php div#continme div#inicio");
		if(laidnoti!='undefined'){
			$("#franja_central").load("noticias.php?idnoti=" + laidnoti + " #franja_central", {}, function () {
				include_dom('js/noticias.js');
				return false;
			});
		}
		else {
			$("#franja_central").load("noticias.php #franja_central", {}, function () {
				include_dom('js/noticias.js');
				return false;
			});
		}
		$("#botonera").load("noticias.php #botonera");
		return false;
	});
	
	$('#boto_contactar').live("click", function () {
		//$("title").text("Tutuning - Homologaciones :: Fichas reducidas :: Reformas de vehículos - Formulario de contacto");		
		//$("#botonera").load("quienes.php #botonera");
		document.title = 'Tutuning - Homologaciones :: Fichas reducidas :: Reformas de vehículos - Formulario de contacto';
		$("#continme div#inicio").load("contactar.php div#continme div#inicio", {}, function () {});
		$("#franja_central").load("contactar.php #franja_central", {}, function () {
			include_dom('js/contactar.js');
		});
		$("#botonera").load("contactar.php #botonera");
		return false;
	});
	
	$('#boto_como, #meshomologa').live("click", function () {
	
		afegeix_estils('js/jquery/ui.all.css');
		
		include_once('js/jquery/jquery.ajax_upload.1.0.js');
		include_once('js/jquery/jquery.json-1.3.min.js');
		include_once('js/jquery/jquery-ui-personalized-1.6rc5.packed.js');
		
		//$("title").text("Tutuning - Homologaciones :: Fichas reducidas :: Reformas de vehículos - Noticias");
		document.title = 'Tutuning - Homologaciones :: Fichas reducidas :: Reformas de vehículos - Noticias';
		$("#continme div#inicio").load("homologar.php div#continme div#inicio", {}, function () {});
		$("#franja_central").load("homologar.php #franja_central", {}, function () {
			include_dom('js/homologar.js');
		});
		$("#botonera").load("homologar.php #botonera");
		return false;
	});
	
	$('#boto_reformas').live("click", function () {
		//$("title").text("Tutuning - Homologaciones :: Fichas reducidas :: Reformas de vehículos - Reformas posibles de vehículos");
		document.title = 'Tutuning - Homologaciones :: Fichas reducidas :: Reformas de vehículos - Reformas posibles de vehículos';
		//$("#botonera").load("quienes.php #botonera");
		$("#continme div#inicio").load("reformas.php #continme div#inicio", {}, function () {
			// no res ací de js
		});
	
		$("#franja_central").load("reformas.php #franja_central", {}, function () {
	
		});
		$("#botonera").load("reformas.php #botonera");
		return false;
	});
	
	$('#boto_gal').live("click", function () {
		
		afegeix_estils("js/jquery/ui.all.css");
		afegeix_estils("js/jquery/jcarousel/lib/jquery.jcarousel.css");
		afegeix_estils("js/jquery/jcarousel/skins/tango/skin.css");
		
		include_once('js/jquery/jquery-ui-personalized-1.6rc5.packed.js');
		include_once('js/jquery/jcarousel/lib/jquery.jcarousel.pack.js');
		include_once('js/jquery/jquery.json-1.3.min.js');
		
		//$("title").text("Tutuning - Homologaciones :: Fichas reducidas :: Reformas de vehículos - Galería de vehículos homologados");
		document.title = 'Tutuning - Homologaciones :: Fichas reducidas :: Reformas de vehículos - Galería de vehículos homologados';
		$("#continme div#inicio").load("galerias.php #continme div#inicio", {}, function () {});
		$("#franja_central").load("galerias.php #franja_central", {}, function () {
			include_dom('js/galerias.js');		
			return false;
		});
		$("#botonera").load("galerias.php #botonera");
		return false;
	});

});