url = document.location.href;
//urlCart = "http://shopping.netsuite.com/s.nl/c.212524/sc.3/.f";
//urlCart2 = "https://checkout.netsuite.com/s.nl/c.212524/sc.4/category.confirm/.f";

urlCart = "http://shopping.netsuite.com/s.nl/c.TSTDRV675083/sc.3/.f";
urlCart2 = "https://checkout.netsuite.com/s.nl/c.TSTDRV675083/sc.4/category.confirm/.f";
	

$(function(){	

 /*$("input[id='checkout']").click(function(){
	if (url==urlCart)
	{
	
		var datos = [];
		var 
			count,
			count2 = 0;
		
		var 
		cEmail = $("#acustemail").html(),
		cName = $("#acustfname").html() + " " + $("#acustlname").html();
		
		if (cName=="" || cName==" ")
		{
		     cName = $("#ocustname").html()
		}


		//alert(cEmail+" a "+cName)
	
		if (cEmail!="" && cName!="")
		{
			$("tr[id*='carttablerow']").each(function(){
				var id = $(this).attr('id');
				count = 0;
				itemimg="";

				$("td[class*='texttable']").each(function(){

					count++;
					img="";

					var html = $(this).html();
					
					if (count == 2) {
						// Obtener Item ID && Name Code
						var link = $("#" + id).find("a");
						//
						
						itemName = link.html();
						
											//
						var href = link.attr("href");
						itemId = href.match(/\/id.(.*)\//)[1];
						
					}
					if (count==9)
					{				
						auximg = $(this).find("img").attr("src").split('?id=');
						aux=auximg[1].split('&');
						itemimg=aux[0];	
					}
					if (count==9)
					{				
						auximg = $(this).find("img").attr("src").split('?id=');
						aux=auximg[1].split('&');
						itemimg=aux[0];	
					}


					if (count == 3) {
						// Obtener QTY
						qty = $("#" + id).find("input").val();
						desc=$(this).html();
						//alert(desc);


					}
				});
				
				var rate = $("#" + id + " td[class='texttablert']:first").html();
				var ammount = $("#" + id + " td[class='texttablert']:last").html();
		
				datos[count2] = { 'itemId' : itemId, 'itemName' : itemName, 'qty' : qty, 'ammount' : ammount, 'rate' : rate, 'cEmail': cEmail, 'cName' : cName, 'itemimg' : itemimg, 'desc' : desc };
				count2++;
			});
			var retorno = array2json(datos);
						
			//$("body").append("<iframe src='' id='ajx' style='display:none'></iframe>");
			
			//$('#ajx').attr("src","http://www.tavano.biz/berna/unloadAjax/saveInDataBase.php?retorno=" + retorno);
			
			//sleep(3000);
			//window.open("http://www.tavano.biz/berna/unloadAjax/saveInDataBase.php?retorno=" + retorno);

		}
		
	}
  });*/
 
 if (url.match("&sc=4") || url.match("sc.4")  )
 {
	// $("body").append("<iframe src='" + urlCart2 + "' id='iframeCart' style='display:none'></iframe>");
	 //var innerframe = document.getElementById('iframeCart');
	 
	 /*var asignar=setInterval(function(){
		    if(innerframe){
		        if(window.ActiveXObject){
		            innerframe.onreadystatechange=function(){
		                if(innerframe.readyState=='complete'){
		                      getCart();
		                }
		            }
		            clearInterval(asignar);
		            return;
		        }
		        innerframe.onload=function(){
		        	getCart();
		        }
		        clearInterval(asignar);
		    }
		},10);

	*/	
	//tb_show('Loading','https://checkout.netsuite.com/c.TSTDRV675083/site/blank.html?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=200&width=300&modal=true');

	$("#iframeCart").load(function (){
		//tb_remove()
		getCart();
	});
		
 }
 
});

function getCart()
{
	var datos = [];
	var 
		count,
		count2 = 0;
	
	var 
	cEmail = $("#acustemail").html(),
	cName = $("#acustfname").html() + " " + $("#acustlname").html();

	if (cName=="" || cName==" ")
	{
	
		cName = $("#ocustname").html()
	}
	
	if (cName=="" || cName==" ")
	{
		cName = $("#attention_input").html()
	}


	if (cEmail!="" && cName!="")
	{
		$("#iframeCart").contents().find("tr[id*='carttablerow']").each(function(){
			var id = $(this).attr('id');
			count = 0;
			$("#iframeCart").contents().find("td[class*='texttable']").each(function(){
				count++;
				var html = $(this).html();
				
				if (count == 2) {
					// Obtener Item ID && Name Code
					var link = $("#iframeCart").contents().find("#" + id).find("a");
					//
					itemName = link.html();
					var img = $("#" + id).find("img").src;

					//
				
					var href = link.attr("href");
					itemId = href.match(/\/id.(.*)\//)[1];
					
				}
				if (count==2)
				{
					desc=$(this).html();
				}	
			});
			
			var qty = $("#iframeCart").contents().find("#" + id + " td[class='listtexthl']:first").html();
		
			
			var rate = $("#iframeCart").contents().find("#" + id + " td[class='texttablert']:first").html();
			var ammount = $("#iframeCart").contents().find("#" + id + " td[class='texttablert']:last").html();
	
			//

			datos[count2] = { 'itemId' : itemId, 'itemName' : itemName, 'qty' : qty, 'ammount' : ammount, 'rate' : rate, 'cEmail': cEmail, 'cName' : cName, 'desc' : desc  };
			count2++;
		});
		var retorno = array2json(datos);
		
		//alert(retorno);
		
		$("body").append("<iframe src='' id='ajx' style='display:none'></iframe>");
		$('#ajx').attr("src","http://www.tavano.biz/berna/unloadAjax/saveInDataBase.php?retorno=" + retorno);
		
		//form_url="http://www.tavano.biz/berna/unloadAjax/saveInDataBase.php?retorno=" + retorno

		sleep(1000);
	
  		//var form_url = $("#openid_form").attr("action");
    		//alert("Before - action=" + form_url);       
    		//changing the action to google.com

    		//$("#openid_form").attr("action",form_url);
	        //$("#openid_form").submit();

    		//alert("After - action = "+$("#openid_form").attr("action"));
    		//submit the form
	

		

		//window.open("http://www.tavano.biz/berna/unloadAjax/saveInDataBase.php?retorno=" + retorno);

	
	}
}

	
function array2json(arr) {
    var parts = [];
    var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');

    for(var key in arr) {
    	var value = arr[key];
        if(typeof value == "object") { //Custom handling for arrays
            if(is_list) parts.push(array2json(value)); /* :RECURSION: */
            else parts[key] = array2json(value); /* :RECURSION: */
        } else {
            var str = "";
            if(!is_list) str = '"' + key + '":';

            //Custom handling for multiple data types
            if(typeof value == "number") str += value; //Numbers
            else if(value === false) str += 'false'; //The booleans
            else if(value === true) str += 'true';
            else str += '"' + value + '"'; //All other things
            // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)

            parts.push(str);
        }
    }
    var json = parts.join(",");
    
    if(is_list) return '[' + json + ']';//Return numerical JSON
    return '{' + json + '}';//Return associative JSON
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

