var debugSearchChilds = new Array();
function searchChild (tagFather, nomeTag, nomeAttributo, valoreAttributo, retrieveCollection) {
	var chiaveDebug = nomeTag + "-" + nomeAttributo + "-" + valoreAttributo;
	var dataCorrente1 = new Date();
	var beginTime = dataCorrente1.getTime();
	var r = performSearchChilds (tagFather, nomeTag, nomeAttributo, valoreAttributo, retrieveCollection);
	var dataCorrente2 = new Date();
	var endTime = dataCorrente2.getTime();
	debugSearchChilds[chiaveDebug]['time'] += parseInt(endTime-beginTime);

	var txt='';
	for(var ii in debugSearchChilds){
		var key = ii.split('-');
		if (key[0] != undefined && key[1] != undefined && key[2] != undefined &&  debugSearchChilds[ii]['time']!= undefined && debugSearchChilds[ii]['cnt'] != undefined ) {
			txt+='<'+key[0]+' '+key[1]+ '="' + key[2]+'"> Tempo ricerca: '+parseInt(debugSearchChilds[ii]['time'])+" #"+debugSearchChilds[ii]['cnt']+" elem\n";
		};

	};
	/*addJSDebug(txt, 'timeSearchChilds');*/
	return r;
}


function searchChild (tagFather, nomeTag, nomeAttributo, valoreAttributo, retrieveCollection) {
	var chiaveDebug = nomeTag + "-" + nomeAttributo + "-" + valoreAttributo;
	var dataCorrente1 = new Date();
	var beginTime = dataCorrente1.getTime();
	var r = performSearchChilds (tagFather, nomeTag, nomeAttributo, valoreAttributo, retrieveCollection);
	var dataCorrente2 = new Date();
	var endTime = dataCorrente2.getTime();
	debugSearchChilds[chiaveDebug]['time'] += parseInt(endTime-beginTime);

	var txt='';
	for(var ii in debugSearchChilds){
		var key = ii.split('-');
		if (key[0] != undefined && key[1] != undefined && key[2] != undefined &&  debugSearchChilds[ii]['time']!= undefined && debugSearchChilds[ii]['cnt'] != undefined ) {
			txt+='<'+key[0]+' '+key[1]+ '="' + key[2]+'"> Tempo ricerca: '+parseInt(debugSearchChilds[ii]['time'])+" #"+debugSearchChilds[ii]['cnt']+" elem\n";
		};

	};
	/*addJSDebug(txt, 'timeSearchChilds');*/
	return r;
}
function performSearchChilds (tagFather, nomeTag, nomeAttributo, valoreAttributo, retrieveCollection) {
	var chiaveDebug = nomeTag + "-" + nomeAttributo + "-" + valoreAttributo;
	if (debugSearchChilds[chiaveDebug] != undefined) {
		debugSearchChilds[chiaveDebug]['cnt']++;
		/* debugSearchChilds[chiaveDebug]['time'] += 2;*/
	} else {
		debugSearchChilds[chiaveDebug] = new Array();
		debugSearchChilds[chiaveDebug]['cnt'] = 1;
		debugSearchChilds[chiaveDebug]['time'] = 0;
	}
	var collection = Array();
	nomeTag = nomeTag.toLowerCase();
	for (var i=0; i < tagFather.childNodes.length; i++) {
		var elem = tagFather.childNodes[i];

		if (elem.tagName != undefined && (elem.tagName.toLowerCase() == nomeTag.toLowerCase() || nomeTag == '*')) {
			if (nomeAttributo == undefined && valoreAttributo == undefined) {
				a = elem;
			} else {
				if (elem.tagName.toLowerCase() == 'label' && nomeAttributo.toLowerCase() == 'for' && (valoreAttributo == undefined || (elem.getAttribute('htmlFor') == valoreAttributo ^ elem.getAttribute('for') == valoreAttributo))) { 
						var a = elem;
				} else if (valoreAttributo == undefined || (nomeAttributo.toLowerCase() == 'class' && elem.className == valoreAttributo)) {
					var a = elem;
				} else if (valoreAttributo == undefined || (nomeAttributo.toLowerCase() == 'checked' && elem.checked != undefined && elem.checked == valoreAttributo)) {
					var a = elem;
				} else if (valoreAttributo == undefined || (elem.getAttribute(nomeAttributo) == valoreAttributo ) ) {
					var a = elem;
				} else {
					if (elem.getAttribute(nomeAttributo) != undefined && isRegExpString(valoreAttributo)) {
						var re = valoreAttributo.replace(/\/$/, '').replace(/^\//,'');
						if (elem.getAttribute(nomeAttributo) != undefined && elem.getAttribute(nomeAttributo).search(new RegExp(re)) != -1) {
							var a = elem;
						}
					};
				};
			}
			if (retrieveCollection != true) {
				if (a != undefined) return a;
			} else {
				if (a != undefined) collection.push(a);
			};
		};

		if (elem.childNodes != undefined && elem.childNodes.length > 0) {
			if (elem.childNodes.length > 0) {
				var b = performSearchChilds(elem, nomeTag, nomeAttributo, valoreAttributo, true);
				if (b != false) {
					if (retrieveCollection != true) {
						return b.pop();
					} else if (b.length > 0) {
						for (var q1 in b) {
							collection.push(b[q1]);
						};
					}
				};
			};
		};
		a = undefined;
	}
	if (collection.length > 0) {
		var ww = Array();
		for (var q in collection) {
			ww[q] = collection[q];
		}
		return ww;
	}
	return false;
}
function trim(txt) {
	txt = txt.replace(/^[\s\t\n\r]+/g, '');
	txt = txt.replace(/[\s\t\n\r]+$/g, '');
	return txt;
}
var oldOnload = new Array();
function addOnload (func) {
	oldOnload.push(func);
}
window.onload = function () {
	var oll = oldOnload.length;
	if (oll > 0) {
		for (var i=0; i<oll; i++) {
			oldOnload[i]();

		}
		/* for (var i in oldOnload) {
			alert(i);
			oldOnload[i]();
		} */
	}
}

function isRegExpString (str) {
	if (str.search(/^\/.*\/[gim]*/) == -1)
		return false;
	return true;
}



var totProdCompare = 0;
var maxProdCompare = 5;
var catProdCompare = '';
var linkCompare = '';
var ptmp = 0;
var inputs;
var imgFalse = '/template/standard/images/false_compare.gif';
var imgTrue  = '/template/standard/images/true_compare.gif';



if (GetCookie('ProdCompare')) {
	linkCompare = GetCookie('ProdCompare');
	prodSplit = linkCompare.split(',');
	totProdCompare = prodSplit.length -1;
	ptmp = prodSplit[0].substring(1, prodSplit[0].length -1);
		for (i=0; i < prodSplit.length-1; i++) {
			if(i==0) ids=prodSplit[i].substring(1, prodSplit[i].length -1);
			else ids = ids +"___"+ prodSplit[i].substring(1, prodSplit[i].length -1);
			pid = prodSplit[i].replace(/"/g, '');
		
    	}
}



function ReplaceCheck() {
		var inputs = document.getElementsByTagName('input');
		var il = inputs.length;

	for (i=0; i < il; i++) {
		if('checkbox' == inputs[i].getAttribute('type') && 'checkCompara' == inputs[i].name) {
			var idCheck = inputs[i].id;
			var id = idCheck.substring(7);

			var img = document.createElement('img');
            var prodotto = document.getElementById('prodotto'+ id);
            var prodottoa = document.getElementById('prodottoa'+ id);

			if(inputs[i].checked) {
				img.src = imgTrue;
                prodotto.className  = 'highlight-compara';
                prodottoa.className = 'bot-highlight-compara';
			} else {
				img.src = imgFalse;
                prodotto.className  = 'no-highlight-compara';
                prodottoa.className = 'no-bot-highlight-compara';
			}
				img.id = 'checkImage'+ id;
				img.className = 'cimg';
			img.onclick = function () {
				var thisId = this.id.substring(10);
				ChangeCheck(thisId);
				InsertProdCompare(thisId);
				ShowCompare(this);
			}

			inputs[i].parentNode.insertBefore(img, inputs[i]);

		}
	}
}
addOnload(ReplaceCheck);


function ChangeCheck(id) {
	var ldoc = document;
	if ('' == catProdCompare && '' != linkCompare && ptmp > 0) {
		if (null != ldoc.getElementById('cats'+ ptmp)) {
            catProdCompare = ldoc.getElementById('cats'+ ptmp).innerHTML;
        } else {
            ClearCompare();
        }
    }
    /*if (null != document.getElementById('cat'+ id)) {
        var cat = document.getElementById('cat'+ id).innerHTML;
        if ('' == catProdCompare) {
            catProdCompare = cat;
        } else {
            if (Trim(cat.toLowerCase()) != Trim(catProdCompare.toLowerCase())) {
                document.getElementById('noteCompara').innerHTML = 'Puoi confrontare solo prodotti della stessa categoria';
                return false;
            }
        }
	}*/

	var input = ldoc.getElementById('compara'+ id);
	var img   = ldoc.getElementById('checkImage'+ id);

    if (null != input) {
		if(input.checked) {
			input.checked = false;
			img.src = imgFalse;
		} else {
			if (totProdCompare == maxProdCompare)  {
				document.getElementById('noteCompara').innerHTML = 'Puoi confrontare al massimo '+ maxProdCompare +' prodotti per volta';
				return false;
			}
			input.checked = true;
			img.src = imgTrue;
		}
	}
    if (null != ldoc.getElementById('noteCompara')) {
        document.getElementById('noteCompara').innerHTML = '';
    }
}


function ShowCompare(elemChk) {
    if (totProdCompare > 0) {
        document.getElementById('divcompara').style.display = 'block';
    	if (navigator.userAgent && navigator.userAgent.indexOf("MSIE 7") >= 0) {
    		document.getElementById('divcompara').style.setAttribute('bottom', '0px');
    		document.getElementById('divcompara').style.setAttribute('position', 'fixed');
        }
    } else {
    	document.getElementById('divcompara').style.display = 'none';
    }
}


function InsertProdCompare(prodId) {
	var input = document.getElementById('compara'+ prodId);

	if (input.checked) {
		AddProdCompare(prodId);
	} else {
		DelProdCompare(prodId);
	}
}


function AddProdCompare(prodId) {

	if (totProdCompare == maxProdCompare) {
		document.getElementById('noteCompara').innerHTML='Puoi confrontare al massimo '+ maxProdCompare +' prodotti per volta';
		return false;
    }
	/*if (null != document.getElementById('cat'+ prodId)) {
		var cat = document.getElementById('cat'+ prodId).innerHTML;
		if ('' == catProdCompare) {
			catProdCompare = cat;
        } else {
			if (Trim(cat.toLowerCase()) != Trim(catProdCompare.toLowerCase())) {
				document.getElementById('noteCompara').innerHTML='Puoi confrontare solo prodotti della stessa categoria';
				return false;
            }
        }
    }*/
	linkCompare = linkCompare +'"'+ prodId +'",';
	SetCookie('ProdCompare', linkCompare, 3600, '/', '', '' );
	var divCompara = document.getElementById('comparacontenuto');
	var imgProd = document.getElementById('imgProd'+ prodId);
	var titoloProd = document.getElementById('titoloProd'+ prodId);
	var templateCompara = document.getElementById('templateCompara');
	var prodotto = document.getElementById('prodotto'+ prodId);
	var categoria = document.getElementById('cat'+ prodId);
	var prodottoa = document.getElementById('prodottoa'+ prodId);

	if (undefined == divCompara || undefined == imgProd || undefined == titoloProd || undefined == templateCompara || undefined == categoria) {
        return false;
    }

	var newProd = templateCompara.cloneNode(true);
	var newImg = searchChild(newProd, 'img', 'class', 'imgCompara');
	var newTitolo = searchChild(newProd, 'div', 'class', 'titoloCompara');

	newImg.src = imgProd.src;
	newTitolo.innerHTML = '<div class="catCompara" id="cats'+ prodId +'">'+ categoria.innerHTML +'</div>'+ titoloProd.innerHTML;

	divCompara.appendChild(newProd);
	newProd.style.display = 'block';
	newProd.id = 'prodCompara'+ prodId;
	totProdCompare++;
	prodotto.className  = 'highlight-compara';
	prodottoa.className = 'bot-highlight-compara';

	return true;
}


function ClearCompare() {
    var PSplit = linkCompare.split(',');
    linkCompare = '';
    catProdCompare = '';
    ptmp = 0;
    var psl = PSplit.length-1;
    var ldoc = document;
    for (i=0; i < psl; i++) {
        var prodId = PSplit[i].substring(1, PSplit[i].length -1);
        var prod = ldoc.getElementById('prodCompara'+ prodId);
        var prodotto = ldoc.getElementById('prodotto'+ prodId);
        var prodottoa = ldoc.getElementById('prodottoa'+ prodId);
        var compara = ldoc.getElementById('compara'+ prodId);

        if (prodotto != null) {
            prodotto.className = 'no-highlight-compara';
            prodottoa.className = 'no-bot-highlight-compara';
        }
        if (prod!=null) {
            prod.parentNode.removeChild(prod);
        }

        ChangeCheck(prodId);
	}
    totProdCompare = 0;
    catProdCompare = '';
    ptmp = 0;
    if (null != ldoc.getElementById('divcompara')) {
        document.getElementById('divcompara').style.display = 'none';
    }
    SetCookie('ProdCompare', linkCompare, 3600, '/', '', '');
}


function DelProdCompare(prodId) {    
	var ldoc = document;
    var prod = ldoc.getElementById('prodCompara'+ prodId);
    var prodotto = ldoc.getElementById('prodotto'+ prodId);
    var prodottoa = ldoc.getElementById('prodottoa'+ prodId);
    linkCompare = linkCompare.replace('"'+ prodId +'",', '');
    SetCookie('ProdCompare', linkCompare, 3600, '/', '', '');
    if (undefined == prod) {
        return false;
    }
    prod.parentNode.removeChild(prod);
    totProdCompare--;
    if (0 == totProdCompare) {
        catProdCompare = '';
        document.getElementById('divcompara').style.display = 'none';
    }
    prodotto.className  = 'no-highlight-compara';
    prodottoa.className = 'no-bot-highlight-compara';

    return false;
}


function RemoveElemCompare(elem) {
	var parentElemId = elem.parentNode.id;
	var prodId = parentElemId.substring(11);
	var prodotto = document.getElementById('prodotto'+ prodId);
	var prodottoa = document.getElementById('prodottoa'+ prodId);

	linkCompare = linkCompare.replace('"'+ prodId +'",', '');
	SetCookie('ProdCompare', linkCompare, 3600, '/', '', '');
	if (prodId.length > 0) {
		var comparaProd = document.getElementById('prodCompara'+ prodId);
		comparaProd.parentNode.removeChild(comparaProd);
		ChangeCheck(prodId);
	}
	totProdCompare--;
	if (0 == totProdCompare) {
		catProdCompare='';
		document.getElementById('divcompara').style.display = 'none';
	}
	    (document.getElementById('compara'+ prodId));

	if (null != prodotto) prodotto.className  = 'no-highlight-compara';
	if (null != prodotto) prodottoa.className = 'no-bot-highlight-compara';

	return true;

}


function GotoCompare() {
    var ids='';
    if (linkCompare) {
    	prodSplit = linkCompare.split(',');
    	for (i=0; i < prodSplit.length-1; i++) {
            if(i==0) ids=prodSplit[i].substring(1, prodSplit[i].length -1);
            else ids = ids +"___"+ prodSplit[i].substring(1, prodSplit[i].length -1);
    	}
    }
    
    
    if (!GetCookie('ProdCompara')) {
		if (totProdCompare > 1)  {
			location.href = '/compara_prodotti.php?ids='+ids;
		}else{
			alert('Almeno 2 prodotti per comparare');
    	}
    } else {
    	if ('' != linkCompare) {
            location.href = '/compara_prodotti.php?ids='+linkCompare;
        } else {alert ('Nessun prodotto da comparare');}
    }
}


function ieFix() {
	var div = document.getElementById('divcompara');
	if (null != div) {
		if (navigator.userAgent && navigator.userAgent.indexOf("MSIE 6") >= 0) {
			div.style.setAttribute('top', null);
        } else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE 7") >= 0) {
			div.style.setAttribute('bottom', '0px');
			div.style.setAttribute('position', 'fixed');
		}
	}
}
addOnload(ieFix);
function GetCookie(name) {
	var start = document.cookie.indexOf(name + "=");
	var len = start + name.length +1;
	if (!start && name != document.cookie.substring(0, name.length)) {
		return null;
    }

    if (-1 == start) {
		return null;
    }

	var end = document.cookie.indexOf(";", len);
	if (-1 == end) {
		end = document.cookie.length;
    }
	return unescape(document.cookie.substring(len, end));
}
function SetCookie(name, value, expires, path, domain, secure) {
	var today = new Date();
	today.setTime(today.getTime());
	if (expires) {
		expires = expires*10*60*60*24;
    }
	var expires_date = new Date(today.getTime() + (expires));
	document.cookie = name +"="+ escape(value) +
		(expires ? ";expires="+ expires_date.toGMTString() : "") +
		(path ? ";path="+ path : "") +
		(domain ? ";domain="+ domain : "") +
		((secure) ? "; secure" : "");

}

