function makeMyFlashPlayer(swfsrc, swfid, width, height, bgcolor){

   document.write("<OBJECT classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0' ID=" + swfid + " WIDTH=" + width + " HEIGHT=" + height + ">" );

   document.write("<PARAM NAME=movie VALUE='"+ swfsrc +"'>\n");

   document.write("<PARAM NAME=menu VALUE=\"false\">\n");

   document.write("<PARAM NAME=quality VALUE=\"high\">\n");

   document.write("<PARAM NAME=wmode VALUE=\"transparent\">\n");

   document.write("<PARAM NAME=bgcolor VALUE=\""+ bgcolor+"\">\n");

   document.write("<EMBED NAME=\"" + swfid + "\" src='" + swfsrc + "' quality=high wmode=transparent menu=false bgcolor=" + bgcolor + " WIDTH=" + width + " HEIGHT=" + height + " TYPE='application/x-shockwave-flash' PLUGINSPAGE='http://www.macromedia.com/go/getflashplayer'></EMBED></OBJECT>" );
}

/* Funçoes do DreamWeaver */
function restaura_img() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function troca_img() { //v3.0
  var i,j=0,x,a=troca_img.arguments;
  document.MM_sr=new Array;
  for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null)
   {
	document.MM_sr[j++]=x;
	if(!x.oSrc)
	 x.oSrc=x.src;
	x.src=a[i+2];
   }
}

function fecha() {
	window.close();
}

function popUp(pagina)
{
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(pagina, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menu=1,resizable=1,width=400,height=300,left =300, top= 200');");
}

/* set homepage for IE */
function SetHomepage() {

	if ( document.all ){
		document.write( '<a href="javascript:history.go(0);" id="icon_blog" onClick="this.style.behavior=\'url(#default#homepage)\';this.setHomePage(\'http://www.sexshopmadeira.com/\');">' );
		document.write( language[ 5 ] + '</a>');
	}	
}

function CreateBookmarkLink() 
{
 	title = "SexShopMadeira - Brinquedos e Fantasias Er�ticas"; 
 	url = "http://www.sexshopmadeira.com";
 	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title); }
	else if(window.opera && window.print) { // Opera Hotlist
		return true; 
	}		
}


function goTo(url_base, elemento) {
	var sE = null, url;
	if(document.getElementById) {
		sE = document.getElementById(elemento);
	} else if(document.all) {
		sE = document.all[elemento];
	}
	if(sE && (url = sE.options[sE.selectedIndex].value)) {
		location.href = url_base + url;
	}
}

function setQuantity(pcID, pnOperation, pnMin, pnMax)
{
	var lnCurrentQuantity = parseInt(document.getElementById(pcID).innerHTML);							  
	var lnNewQuantity     = lnCurrentQuantity ; 
	switch(pnOperation)
	{				   
		case 1: // increase quantity by 1 
			lnNewQuantity++	;
			if(lnNewQuantity > pnMax)
			{								
				lnNewQuantity = lnCurrentQuantity ;
			}
			break;
		case 2:// decrease quantity by 1
			lnNewQuantity-- ;
			if(lnNewQuantity < pnMin) 
			{
				lnNewQuantity = lnCurrentQuantity ;
			}
			break;
		default:// ensuring a typed quantity remains within the parameters defined
			if (lnCurrentQuantity > pnMax || lnCurrentQuantity < pnMin)
			{									 
				alert("Please set the quantity as a number between " + pnMin + " and " + pnMax + '\n' + "The quantity will now be set to " + pnMin) ;
				lnNewQuantity = pnMin ;
			}
			break;
	}
	var pFinal = 'preco_final';
	var pFinalValue = document.getElementById('preco_base').value;
	var neb_unidades = document.getElementById('neb_unidades');
	neb_unidades.value = lnNewQuantity;	
	document.getElementById(pFinal).innerHTML = 'Preço: ' + parseFloat((pFinalValue * parseFloat(lnNewQuantity))).toFixed(2)  + ' €';
	document.getElementById(pcID).innerHTML = lnNewQuantity;
}



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

/*
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
			//oldonload();
            //func();
        }
    }
}
*/
function moveSlideshow(elementID,final_x,final_y,interval) {
    if (!document.getElementById) return false;
    
    // if the element does not exist we have nothing to do
    if (!document.getElementById(elementID)) return false;
    var elem = document.getElementById(elementID);
    
    // the slideshow events stack up and the animation is not smooth anymore
    if (elem.movement) {
        clearTimeout(elem.movement);
    }
    
    // current slideshow position
    var xpos = parseInt(elem.style.left);
    var ypos = parseInt(elem.style.top);
    if (xpos == final_x && ypos == final_y) {
        return true;
    }
    
    // restrict moving to white area
    if ((final_x - 484) <= -elem.max_x) {
        final_x = -(elem.max_x - 484);
    }
    if (final_x > 0) {
	    final_x = 0;
    }
    
    // animation bit (taken from the book DOM Scripting by Jeremy Keith)
    if (xpos < final_x) {
        var dist = Math.ceil((final_x - xpos)/10);
        xpos = xpos + dist;
    }
    if (xpos > final_x) {
        var dist = Math.ceil((xpos - final_x)/10);
        xpos = xpos - dist;
    }
  
    // again, restrict showing white area
    if (xpos <= -elem.max_x) {
	    xpos = -elem.max_x;
    }
    if (xpos > 0) {
	    xpos = 0;
    }
    
    // fix the elements position
    elem.style.left = xpos + "px";
    elem.style.top = ypos + "px";
    
    // and set up the event again after an interval
    var repeat = "moveSlideshow('"+elementID+"',"+final_x+","+final_y+","+interval+")";
    elem.movement = setTimeout(repeat,interval);
}

function prepareSlideshow() {
	// first lets make sure the browser understands the DOM methods we will be using
	
  	if (!document.getElementsByTagName) return false;
  	if (!document.getElementById) return false;
  	
	// Make sure the elements exist
  	if (!document.getElementById("slideshow")) return false;
  	var slideshow = document.getElementById("slideshow");
  	var wrapper = document.getElementById("slideshow_wrapper");
  	wrapper.style.overflow = "hidden";
  	
  	// prepare the navigation bit we will be using
  	// left
  	var navigation = document.createElement("ul");
  	navigation.setAttribute("id", "navigation");
  	var li = document.createElement("li");
  	var scroll_left = document.createElement("a");
  	scroll_left.setAttribute("id", "scroll_left");
  	scroll_left.href ="#";
  	var text = document.createTextNode("Left");
  	scroll_left.appendChild(text);
  	li.appendChild(scroll_left);
  	navigation.appendChild(li);
  	slideshow.insertBefore(navigation, wrapper);
  	
  	//right
  	var li = document.createElement("li");
  	var scroll_right = document.createElement("a");
  	scroll_right.setAttribute("id", "scroll_right");
  	scroll_right.href ="#";
  	var text = document.createTextNode("Right");
  	scroll_right.appendChild(text);
  	li.appendChild(scroll_right);
  	navigation.appendChild(li);
  	slideshow.insertBefore(navigation, wrapper);
	
	var slideshow_set = document.getElementById("slideshow_set");
	slideshow_set.style.top = 0+"px";
	slideshow_set.style.left = 0+"px";
	
	// to get the max y position of the gallery image track we need to count all
	// the li items and multiply that number with 130
	var li = slideshow_set.getElementsByTagName("li");
	slideshow_set.max_x = (li.length-1) * 121;
	slideshow_set.max_y = li.length * 112;
	
	// need the width of the gallery so that they do not scroll vertical
	var width = (li.length * 121);
	slideshow_set.style.width = width + "px";
	
	// Attach onmouseover event for left
  	scroll_left.onclick = function() {
		// get the current position of the gallery element
		var slideshow_set = document.getElementById("slideshow_set");
		var x = parseInt(slideshow_set.style.left);
		if (x % 121 == 0) {
    		moveSlideshow("slideshow_set",x+121,0,10);
		}
		return false;
	}
	
	// Attach onmouseover event for right
  	scroll_right.onclick = function() {
		// get the current position of the gallery element
		var slideshow_set = document.getElementById("slideshow_set");
		var x = parseInt(slideshow_set.style.left);
		//alert(parseInt((document.getElementById("slideshow_set")).max_x));
		//alert(x-121);
    	if (x % 121 == 0) {
    		moveSlideshow("slideshow_set",x-121,0,10);
		}
		return false;
	}
}

var pedido = "";
function add_cart() {

	//preparar a string para post
	var poststr = pedido;
	poststr += "&unidades=" + encodeURI( document.getElementById("neb_unidades").value );
	var opt_cat = 0;
	while((document.getElementById("opt_cat_" + opt_cat) != null))
	{
		poststr +="&opt_cat_" + opt_cat + "=" + encodeURI( document.getElementById("opt_cat_" + opt_cat).value );
		var i = 0;
		while((document.getElementById("opt_item_" + opt_cat + "_" + i ) != null)){
			var my_objecto = document.getElementById("opt_item_" + opt_cat + "_" + i);
			if(my_objecto.checked) {
				poststr +="&opt_item_sel_" + opt_cat + "=" + encodeURI( my_objecto.value );
			}
			i++;
		}		
		opt_cat = opt_cat + 1;
		
	}
	
	var extras_ad = 0;
	var extra = 0;
	while((document.getElementById("extra_" + extra) != null))
	{
		if(document.getElementById("extra_valor_" + extra) !=null)
		{
			if(document.getElementById("extra_valor_" + extra).checked )
			{
				poststr +="&extra_" + extras_ad + "=" + encodeURI( document.getElementById("extra_" + extra).value );
				extras_ad = extras_ad + 1;
			}
		}
		extra++;
		
	}
	
	//alert(poststr);
	//if (!document.getElementById("cartform")) return false;
	//document.getElementById("cartform").submit();
	//var poststr = "utilizador=" + encodeURI( document.getElementById("utilizador").value );
    //              "&password=" + encodeURI( document.getElementById("password").value );
    makePOSTRequest('/cart/adiciona', poststr);
	
	
	
	
	//my_form.submit();
	//alert('ola');
}

/* 	A componente de javascript para o cart tem por base o componente SlideShow( Não é nativo da Nebulae ) 
	O objectivo é que o cart seja utilizado independentemente do suporte do browser do cliente para javascript
*/
function preparaCart() {
	
	//if(!document.getElementByTagName) return false;
	if(!document.getElementById) return false;
	
	if( !document.getElementById("nebulae_cart")) return false;
	var neb_cart = document.getElementById("nebulae_cart");
	
	
	//ocultar o link de adicionar ao cart por post
	var neb_cart_oadd = document.getElementById("btn_adiciona");
	neb_cart_oadd.style.display = "none";
	
	//instalar o botao ajax
	var adiciona = document.createElement("a");
	adiciona.setAttribute("id", "cart_adiciona");
	adiciona.href="#1";
	
	//criar a imagem
	//<img  alt="<?=PRODUTOS_ADICIONAR_CESTO?>" title="<?=PRODUTOS_ADICIONAR_CESTO?>" onmouseover="this.style.cursor='pointer';"  onclick="AdicionaCesto();"/>
	var img_cart = document.createElement("img");
	img_cart.setAttribute("src", "/public/images/template/cesto_pt.gif");
	img_cart.setAttribute("alt", "Adicionar ao cesto");
	img_cart.setAttribute("title", "Adicionar");
	img_cart.setAttribute("onmouseover", "this.style.cursor=\'pointer\';");
	img_cart.setAttribute("onrelease", "add_cart();");
	
	adiciona.appendChild(img_cart);
	neb_cart.appendChild(adiciona);
	
	adiciona.onclick = function() {
		add_cart();
	}
	
	pedido = "produto=" + encodeURI( document.getElementById("neb_produto").value ) +
			"&variante=" + encodeURI( document.getElementById("neb_variante").value );
}

var http_request = false;
function makePOSTRequest(url, parameters) {
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
        }
    } else if (window.ActiveXObject) { // IE
        try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
	}
    if (!http_request) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }
    
	
    http_request.onreadystatechange = alertContents;
    http_request.open('POST', url, true);
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http_request.setRequestHeader("Content-length", parameters.length);
    http_request.setRequestHeader("Connection", "close");
    http_request.send(parameters);
}
	
function makeHTTPRequest(url) {
    http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			// set type accordingly to anticipated content type
			//http_request.overrideMimeType('text/xml');
			http_request.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
    if (!http_request) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }
      
    http_request.onreadystatechange = utilizador_handle;
    http_request.open('GET', url, true);
    //http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //http_request.setRequestHeader("Content-length", parameters.length);
    //http_request.setRequestHeader("Connection", "close");
    http_request.send(null);
}
   
function utilizador_handle()
{
  	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
            result = http_request.responseText;
            document.getElementById('login_client').innerHTML = result;
            tb_remove();
		}
    }
}
   
function alertContents() {
    if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			
			//alert(http_request.responseText);
            result = http_request.responseText;
            if(result.substring(0,2) != "OK")
            {
		//Update Cart html
            	//document.getElementById('resposta').innerHTML = result;
		actualiza_totais('/cart/get_total');
		anim_adicionado();
            } else {
				
            }            
        } else {
	
	}
    }
}

function actualiza_totais(url) {
    http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			// set type accordingly to anticipated content type
			//http_request.overrideMimeType('text/xml');
			http_request.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
    if (!http_request) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }
      
    http_request.onreadystatechange = update_banner;
    http_request.open('GET', url, true);
    http_request.send(null);
}

function actualiza_itens(url) {
    http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			// set type accordingly to anticipated content type
			//http_request.overrideMimeType('text/xml');
			http_request.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
    if (!http_request) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }
      
    http_request.onreadystatechange = update_banner_itens;
    http_request.open('GET', url, true);
    http_request.send(null);
}

function update_banner()
{
	if (http_request.readyState == 4) 
	{
		if (http_request.status == 200) 
		{
	            result = http_request.responseText;
		    var tmp = document.getElementById("banner_total_cart");
		    tmp.innerHTML = result + ' €';
		    actualiza_itens('/cart/get_itens');
		}
	}
}

function update_banner_itens()
{
	if (http_request.readyState == 4) 
	{
		if (http_request.status == 200) 
		{
	            result = http_request.responseText;
		    var tmp2 = document.getElementById("banner_num_itens");
		    tmp2.innerHTML = result;
		}
	}
}

/*   
function get(obj) {

    var poststr = "utilizador=" + encodeURI( document.getElementById("utilizador").value ) +
                  "&password=" + encodeURI( document.getElementById("password").value );
    makePOSTRequest('/clientes/do_login', poststr);
}
*/

   
$(document).ready(function() {
	//prepareSlideshow();
	preparaCart();
          // put all your jQuery goodness in here.
});


var intervalID;  
function anim_adicionado()  
{  
	intervalID = setInterval(flashText, 4000);
	var my_anim = document.getElementById("anim_adicionado");
	my_anim.style.display = '';
}  
   
function flashText()  
{  
	var my_anim = document.getElementById("anim_adicionado");
	my_anim.style.display = 'none';
	clearInterval(intervalID);
}

function add_bookmark() {
	var url      = "http://www.decoracao-casa.com";
	var title    = "Decoracao-casa - Decore a sua casa";
	if (window.sidebar) 
		window.sidebar.addPanel(title, url,"");
	else if(window.opera && window.print){
	        var mbm = document.createElement('a');
        	mbm.setAttribute('rel','sidebar');
        	mbm.setAttribute('href',url);
        	mbm.setAttribute('title',title);
        	mbm.click();
    	}
    	else if(document.all){
		window.external.AddFavorite(url, title);
	}
}

