function addLoadEvent(func)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}

}

function hkp() {
	    new Ajax.Updater('main_content', 'http://localhost:3000', {asynchronous:true, evalScripts:true}); 
}

/*
function protectInputs() {
   if(!document.getElementsByTagName){ return; }
	var inputs = document.getElementsByTagName("input");

	for (var i=0; i<inputs.length; i++){
     	var input = inputs[i];

		if (input.getAttribute("type") == "heineken" ) {
			input.onclick = function () {this.disabled = true; return true;}
		}
	}
}
*/

function removeActiveXBorder() {
   theObjects = document.getElementsByTagName("object");
   for (var i = 0; i < theObjects.length; i++) {
      theObjects[i].outerHTML = theObjects[i].outerHTML;
   } 
}

// Empieza marquee
var a, pause=0,position=0;
function slide() {
   clearTimeout(a)
   if(arguments[0]) {
      clearTimeout()
      position = 0;
      pause = 0;
      }
   if(document.getElementById('marquee')) {
        // variables declaration
        var i,k,msg="                                                                                    Los e-codes válidos para obtener artículos del catálogo de HeinekenProfesional.com son distintos a los Pin-Codes del Club Heineken al consumidor (www.heineken.es). Los códigos para los consumidores se encuentran en los pack de 6 botellas 25cl No Retornables y en los pack de 4 botellas de 33cl no retornables que sólo se venden en el canal de alimentación y nunca en Hostelería.                                                                                                Recuerda que es necesario conservar los cover-crates que has utilizado para conseguir tus e-codes";

        // increase msg
        //k=(300/msg.length)+1;
        //for(i=0;i<k; i++) msg+="  "+msg;

        //show it to window
        valor = msg.substring(position,position+100);
        document.getElementById('marquee').value = valor

        //set new position
        if(position++==658) position=0;
        if(position == 460) document.getElementById('marquee').style.color = '#90e78a'
        else if(position == 658) document.getElementById('marquee').style.color = '#FFFFFF'

        // repeat at entered speed
        a=setTimeout("slide()",85) ;
   }
}

function betycodes(nick, password, canal, idpromo) {
   if(idpromo) str ="http://catalogo.heinekenprofesional.com/web/login_automatico_heineken?NICK="+nick+"&PASSWORD="+password+"&CANAL="+canal+"&idpromo="+idpromo
 else str = "http://catalogo.heinekenprofesional.com/web/login_automatico_heineken?NICK="+nick+"&PASSWORD="+password+"&CANAL="+canal
 //  else str = "http://heineken.betycode.betybyte.local/web/login_automatico_heineken?NICK="+nick+"&PASSWORD="+password+"&CANAL="+canal
   bCodes = window.open(str,"betycodes"); 
}
function barrel(nick, password) {
	str = "http://catalogo.heinekenprofesional.com/web/catalogo_barril?NICK="+nick+"&PASSWORD="+password
	bCodes = window.open(str,"betycodes");
}
function course(nick, password) {
	str = "http://catalogo.heinekenprofesional.com/web/catalogo_sin_gastos?NICK="+nick+"&PASSWORD="+password+"&idpromo=374"
	crs = window.open(str,"betycodes");
}

function ventana(doc, width, height) {
  win = window.open(doc,'','width='+width+',height='+height+'');
}

var bannerIsOn;
function initBanner() {
   bannerIsOn = true
}

// Empieza Flash
function setBannerProfile() {
   if(bannerIsOn) thisMovie("banner").ping();
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName]
    }
    else {
        return document[movieName]
    }
} 
// Acaba Flash

//addLoadEvent(protectInputs);
addLoadEvent(slide)
//addLoadEvent(removeActiveXBorder);

// Cookies
function setCookie(name,value,days) {
   if(days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function delCookie(name) {
	setCookie(name,"",-1);
}

function cookieCheck() {
   var cookies = false;
   setCookie('CookieCheck', 1,1)
      
   if(getCookie('CookieCheck')) cookies = true;
   else cookies = false;
   
   if(cookies) delCookie('CookieCheck');
   return cookies;
}

// AJAX
function ajaxCheck() {
   if(XMLHttpRequest()) return true;
   else return false;
}

function go_home() {
   setBannerProfile()
   new Ajax.Updater('main_content', '/home/', {asynchronous:true, evalScripts:true});
   return true;
}

function go_url(url) {
   unFocus.History.addHistory(url)
   //new Ajax.Updater('main_content', url, {asynchronous:true, evalScripts:true}); 
   //loader.location="/main/loader?url="+url+"&update=main_content"
}

function appear() {
   new Effect.Appear(arguments[0])
   return true;
}

function packages() {
   new Ajax.Updater('main_content','/home/packages/', {asynchronous:true, evalScripts:true});
   return true;
}

function establishment_complete() {
     new Ajax.Updater('main_content','/user/establishments/', {asynchronous:true, evalScripts:true});
     return true;
}

function set_rating(id,stars) {
   star_width = 17
   document.getElementById('current_'+id).style.width = stars*star_width+'px'
   document.getElementById('hidden_'+id).value = stars
}

function recipe_rating(id,stars) {
    url = '/recipes/vote/'+id+'/?stars='+stars
    go_url(url)
}

function select_all_messages(selected) {
	form = document.getElementById('messages_form')
	if(selected) {
		for(i=0;i<form.elements.length;i++) {
    		if(form.elements[i].getAttribute('type') == "checkbox") form.elements[i].checked = true
  		}
	} else {
		for(i=0;i<form.elements.length;i++) {
    		if(form.elements[i].getAttribute('type') == "checkbox") form.elements[i].checked = false
  		}		
	}
	
}
var _chat_window
function chat() {
	if(_chat_window != null) _chat_window.focus()
	else {
		left_position = (screen.width) ? (screen.width-622)/2 : 0;
		top_position = (screen.height) ? (screen.height-620)/2 : 0;		
		a = window.open('http://www.heinekenprofesional.com:9000/chat/', 'chat', 'width=622,height=620,resizable=no,scrollbars=no,status=no,top='+top_position+',left='+left_position+'')
		}
}
function InsertarImagen()
{
	document.getElementById('formulario').action = "/establishment_contents/addImagenContenido";
   	document.getElementById('formulario').submit();
}
function EliminarImagen()
{
	document.getElementById('formulario').action = "/establishment_photos/destroy";
   	document.getElementById('formulario').submit();
}

function cambio()
{
	document.getElementById('etiqueta').value=document.getElementById('establishment_photo_uploaded_data').value;
}

function handleResponse(documentObject,stringToEvaluate) {
	window.eval(stringToEvaluate);
	if (documentObject.location){ // Should be usefull for IE only .. but I cannot test it
		if (documentObject.location != "") 
			documentObject.location.replace('about:blank');
	}
}

var _upload_window
function market_upload(id) {
	if(_chat_window != null) _chat_window.focus()
	else {
		left_position = (screen.width) ? (screen.width-554)/2 : 0;
		top_position = (screen.height) ? (screen.height-378)/2 : 0;		
		a = window.open('/market/upload/'+id, 'upload', 'width=554,height=378,resizable=no,scrollbars=no,status=no,top='+top_position+',left='+left_position+'')
		}
}


function newStyleSheet(css) {
	if(css) {
		if(document.getElementById('custom_css')) {
			document.getElementById('custom_css').href = "/stylesheets/"+css
		} else {	
			l = document.createElement("LINK")
			l.setAttribute("type", "text/css")
			l.setAttribute("rel", "Stylesheet")
			l.setAttribute("id", "custom_css")		
			l.setAttribute("href", "/stylesheets/"+css)
			document.getElementsByTagName("HEAD")[0].appendChild(l)
		}
	}
}
function InsertarImagen()
{
	document.getElementById('formulario').action = "/establishment_contents/addImagenContenido";
   	document.getElementById('formulario').submit();
}
function EliminarImagen()
{
	document.getElementById('formulario').action = "/establishment_photos/destroy";
   	document.getElementById('formulario').submit();
}

function cambio()
{
	document.getElementById('etiqueta').value=document.getElementById('establishment_photo_uploaded_data').value;
}

function handleResponse(documentObject,stringToEvaluate) {
	window.eval(stringToEvaluate);
	if (documentObject.location){ // Should be usefull for IE only .. but I cannot test it
		if (documentObject.location != "") 
			documentObject.location.replace('about:blank');
	}
}																																							

function hkad_back() {
  $('hkad_video').innerHTML = ""
  $('hkad_video').style.display = 'none'
  $('hkad_link').style.display = 'none'
  $('hkad_container').style.display = 'block'
}

function hkad(hash, width, height) {
str = "<object width=\""+width+"\" height=\""+height+"\">"
str += "<param name=\"movie\" value=\"http://www.youtube.com/v/"+hash+"&hl=es_ES&fs=1&autoplay=1\"></param>"
str += "<param name=\"allowFullScreen\" value=\"true\"></param>"
str += "<param name=\"allowscriptaccess\" value=\"always\"></param>"
str += "<embed src=\"http://www.youtube.com/v/"+hash+"&hl=es_ES&fs=1&autoplay=1\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\""+width+"\" height=\""+height+"\"></embed>"
str += "</object>"

$('hkad_video').innerHTML = str

$('hkad_video').style.display = 'block'
$('hkad_link').style.display = 'block'
$('hkad_container').style.display = 'none'

}
function eula() {
  ventana('/eula.html',500, 400)
}

// My mini "Ajax" (DHTML) app
function HistoryKeeper() {
	// some application vars
	var stateVar = "nothin'", displayDiv = document.getElementById("main_content");
	// This is the method that will recieve notifications from the History Keeper,
	// which will then update the state of the app.
	// :NOTE: This will be called when a new entry is added.
	// :NOTE: This will be called if another app on the page sets a history,
	//        so you will need to watch out for this, if you have more than
	//        one script using the history keeper, by doing some kind of 
	//        check to make sure that the new hash belongs to this app.
	//        I wouldn't expect this to be a problem all that frequently.
	this.historyListener = function(historyHash) {
		// update the stateVar
		stateVar = historyHash;
		// update display content
                if(historyHash == "") historyHash = '/home'
                hk_current_hash = historyHash
                if(historyHash.indexOf("/") != -1) new Ajax.Updater('main_content', historyHash, {asynchronous:true, evalScripts:true})
		// update document title
//		document.title = "unFocus History Keeper - Current History: " + historyHash;
	};
	// subscribe to unFocus.History
	unFocus.History.addEventListener('historyChange', this.historyListener);
	
	// Check for an initial value (deep link).
	// In this demo app, the historyListener can handle the task.
	this.historyListener(unFocus.History.getCurrent());
};
// instantiate and inialize the app. DOM has to be ready so we can get a ref to
// the HistoryState DOM element (aka the view), so we use QuickLoader to make
// sure it's ready
//
//

var hk_current_hash = '/news'

Ajax.Responders.register({
	onComplete: function(request){
  // Check if urchinTracker function is available.
      pageTracker._trackPageview(request.url);
	}
});

