/** 
 * When the checkbox is set to true on the HTML page, this functions triggers and add/remove the product id to the compare array
 */
var items = new Array();

function setItemtoCompare(event){
    event = event || window.event;
    var chk = event.target || event.srcElement;
    
    if (chk.checked == true) /* ADD the product to the compare array */ 
        items[items.length] = chk.name;
    else /* the product was already in the compare array: find and REMOVE */ 
        for (i in items) 
            if (items[i] == chk.name) 
                items.splice(i, 1);
}


/** 
 * Start the compare popup:
 *		- see if any items have been added to the compare array
 *		- create a wireframe to display data
 *		- replenish the wireframe with the compare data
 *		- display the compare
 */
var displayed = 0;
var wireframe = null;
function startCompare(){
    if (items.length > 1) {
        displayed = items.length;
        wireframe = createWireframe(); /* very IMPORTANT: set global variable with referred wireframe */
        loadCompareData();
        
        //document.getElementsByTagName("body")[0].appendChild(wireframe);	
        
        displayCompare(wireframe);
    }
    else 
        alert('Please select 2 or more items to compare');
}


/**
 * 	Creates a Wireframe with the following format:
 *	<div id="comparewrapper">
 *		<div id="comparewireframe">
 *			<div id="comparetop"><a href="javascript:Page(1)" class="compareexit" title="exit compare">Exit</a></div>
 *			<div id="comparedata">
 *				<table class="comparetabledata" align="center" border="0" cellspacing="0" cellpadding="0">
 *					<!-- first COLUMN of labels for each row of data -->
 *				<table>
 *			</div>
 *		</div>
 *	</div>
 */
var compareRowsClass = 'firstRowColumn';
var numRows = 0;
function createWireframe(){
    numRows = 0;
    var cwrapp = document.createElement('div');
    cwrapp.id = 'comparewrapper';
    var cpwf = document.createElement('div'); /* create the wireframe div object */
    cpwf.id = 'comparewireframe';
    var cptop = document.createElement('div');
    cptop.id = 'comparetop';
    cptop.innerHTML = '<span class="comparetoptitle">Product Comparison</span><a href="javascript:removeCompare()" class="compareexit" title="exit compare">Exit</a>';
    var cpdata = document.createElement('div');
    cpdata.id = 'comparebottom';
	cpdata.innerHTML = "Show differences <input type='checkbox' onclick='highlightDifferentAttrs()'>";
    var tbl = document.createElement('table');
    tbl.id = 'comparetabledata';
    var tblBody = document.createElement("tbody");
    appendRow(tblBody, compareRowsClass, 'removeitem', ''); /* first row will be used for the remove button */
    numRows++;
    
    /* get first item to compare and create first column of labels */
    var firstitem = document.getElementById('comparedata_' + items[0]);
    if (firstitem) {
        var comparedivs = firstitem.getElementsByTagName('div');
        for (var d in comparedivs) {
            if (comparedivs[d].className == 'cdata' || comparedivs[d].className == 'clabel') {
                appendRow(tblBody, compareRowsClass, 'cfirstcol', ((comparedivs[d].className == 'clabel') ? comparedivs[d].title : ''));
                numRows++;
            }
        }
    }
    
    tbl.appendChild(tblBody);
    
    tbl.setAttribute("border", "0"); /* set attributes for table */
    tbl.setAttribute("cellspacing", "0");
    tbl.setAttribute("cellpadding", "0");
    
    cpdata.appendChild(tbl);
    
    cpwf.appendChild(cptop);
    cpwf.appendChild(cpdata);
    
    cwrapp.appendChild(cpwf);
    return (cwrapp);
}


/**
 *	helper function to create rows
 */
function appendRow(tableBody, rowClass, cellClass, cellinnerHTML){
    var row = document.createElement('tr');
    row.setAttribute('id', 'compare-row-' + numRows)
    if (rowClass != 'undefined') 
        row.className = rowClass;
    var cell = document.createElement('td');
    if (cellClass != 'undefined') 
        cell.className = cellClass;
    if (cellinnerHTML != 'undefined') 
        cell.innerHTML = cellinnerHTML;
    cell.setAttribute('vAlign', 'top');
    row.appendChild(cell);
    tableBody.appendChild(row);
}


/**
 *	LOADS the data of the items to compare into the wireframe
 */
function loadCompareData(){

    if (!wireframe) 
        return;
    var auxRows = wireframe.getElementsByTagName("table")[0].getElementsByTagName("tr"); /* get all the rows in wireframe */
    /* 	Filter rows that are not part of the Compare Wireframe. 
     This is specifically for solving problem with quantity pricing tables has appeared in Bamboo F. */
    var rows = [];
    for (var r = 0; r < auxRows.length; r++) 
        if (auxRows[r].className == compareRowsClass) 
            rows[rows.length] = auxRows[r];
    
    
    for (var i = 0; i < items.length; i++) { /* while there are items to display */
        var comparedata = document.getElementById('comparedata_' + items[i]); /* retrieve divs from DOM with data */
        if (comparedata) {
        
            var row_count = 0; /* data is entered in each row by position, so we need a varible to keep track of the rows fulfilled */
            /* first remove button */
            var removeButton = '<a href="javascript:removeItem(\'td_' + i.toString() + '\')" title="remove item" class="compareremove">remove</a>';
            insertData(rows, removeButton, row_count++, i);
            
            var comparedivs = comparedata.getElementsByTagName('div');
            for (var d in comparedivs) {
                if (comparedivs[d].className == 'cdata' || comparedivs[d].className == 'clabel') {
                    insertData(rows, comparedivs[d].innerHTML, row_count++, i);
                }
            }
        }
    }
    hideEmptyRows(rows);
}


/**
 *	helper function to insert data
 */
function insertData(rows, html, rownum, i){
    var td = document.createElement("td"); // create a new TD
    td.setAttribute('vAlign', 'top');
    td.id = "tr" + rownum.toString() + "_td_" + i.toString(); // assign ID, allows to remove it later 
    td.className = "compareValues"; // assign a class for CSS styles
    td.innerHTML = html; // write the HTML  inside the TD
    var row = rows[rownum];
    row.appendChild(td); // put the new td in the cell array
    if (rownum > 2) {
        GPR_UTILS.compareHelper.addData(row, html)
    }
}


/**
 * remove an item from the compare wireframe
 */
function removeItem(td_id){
    var diffshightlited = false;
    if (--displayed > 2) {
        GPR_UTILS.compareHelper.removeData(parseInt(td_id));
        for (var r = 0; r < numRows; r++) {
            var cell = document.getElementById("tr" + r.toString() + "_" + td_id);
            if (cell) {
                cell.innerHTML = ' ';
                removeObject(cell);
                if (!diffshightlited && GPR_UTILS.DOMTools.hasClass(document.getElementById('compare-row-' + r), "highlight")) {
                    diffshightlited = true;
                }
            }
            else {
                continue
            }
        }
        if (diffshightlited) {
            /* Highlight differences again. */
            highlightDifferentAttrs();
            highlightDifferentAttrs()
        }
        document.getElementById('comparewireframe').style.width = (110 + 250 * displayed) + 'px'; /* set width of the wireframe */
    }
    else {
        /* NO sense in showing the compare if there is only one product */
        removeCompare()
    }
}


/**
 * Hide every row that didn't load actual values
 */
function hideEmptyRows(rows){
    var count = 0, cells, empty;
    
    for (var r = 2; r < rows.length; r++) {
    
        cells = rows[r].getElementsByTagName("td");
        empty = true;
        
        for (var c = 1; c < cells.length; c++) 
            if (!(/^\s*$/.test(cells[c].innerHTML))) // check if empty
                empty = false; // cell needs to have some child and not blank
        /* only if it is a row of the wireframe (not of inner tables) */
        if (rows[r].className.indexOf(compareRowsClass) > -1) {
            if (empty) 
                removeObject(rows[r]);
            else 
                rows[r].className += (count++ % 2 == 0) ? " even" : " odd"; // assign a class for CSS styles			
        }
    }
}


/**
 * 	Remove the compare from the DOM
 */
function removeCompare(){
    visibilitySelectsIE(true);
    if (document.getElementById('blur')) 
        removeObject(document.getElementById('blur'));
    if (wireframe) {
        wireframe.innerHTML = '';
        removeObject(wireframe);
    }
    GPR_UTILS.compareHelper.clearCollection();
}


/**
 * 	Show blur screen and display compare wireframe
 */
function displayCompare(){

    visibilitySelectsIE(false);
    
    div = document.createElement("div");
    div.id = "blur";
    div.onclick = function(){
        removeCompare();
    };
    
    var h = document.body.offsetHeight; /* calculate the size of the blur */
    var h_a = document.body.scrollHeight;
    h = (h > h_a) ? h : h_a;
    var w = document.body.offsetWidth;
    
    /*	div.style.width = w+'px';	*/
    /* better to set the width by styles */
    div.style.height = h + 'px';
    
    window.scroll(0, 0);
    document.getElementsByTagName("body")[0].appendChild(wireframe);
    document.getElementsByTagName("body")[0].appendChild(div);
    
    wireWidth = 110 + 250 * displayed; /* set width of the wireframe */
    document.getElementById('comparewireframe').style.width = wireWidth + 'px';
    
    var leftDif = w - wireWidth;
    var left = (leftDif > 0) ? (leftDif / 2) : 1;
    if (/MSIE/.test(navigator.userAgent)) 
        document.getElementById('comparewrapper').style.left = left + 'px'; /* align problem on IE */
    else 
        document.getElementById('comparewireframe').style.marginLeft = left + 'px';
}


/* hide selects on IE */
function visibilitySelectsIE(flag){
    var n = navigator.userAgent;
    if (/MSIE/.test(n)) {
        selects = document.getElementsByTagName("select");
        for (var i = 0; i < selects.length; i++) 
            selects[i].style.visibility = (flag) ? "visible" : "hidden";
    }
}

/* remove an object from the DOM */
function removeObject(obj){
    if (obj) 
        obj.parentNode.removeChild(obj);
}

function highlightDifferentAttrs(){
    var rows = GPR_UTILS.compareHelper.getRowsWithDifferentValues(), len = rows.length;
    if (GPR_UTILS.DOMTools.hasClass(rows[0], "highlight")) {
        for (var i = 0; i < len; i++) {
            GPR_UTILS.DOMTools.removeClass(rows[i], "highlight")
        }
    }
    else {
        for (var i = 0; i < len; i++) {
            GPR_UTILS.DOMTools.addClass(rows[i], "highlight")
        }
    }
    
}


//---- Cross-browser add/remove event functions --------------------------
function addEvent(obj, evType, fn, useCapture){
    if (obj.addEventListener) {
        obj.addEventListener(evType, fn, useCapture);
        return true;
    }
    else 
        if (obj.attachEvent) {
            return (obj.attachEvent("on" + evType, fn));
        }
        else 
            return false;
}

function removeEvent(obj, evType, fn, useCapture){
    if (obj.removeEventListener) {
        obj.removeEventListener(evType, fn, useCapture);
        return true;
    }
    else 
        if (obj.detachEvent) {
            return (obj.detachEvent("on" + evType, fn));
        }
        else 
            return false;
}

//------------------------------------------------------------------------

/* Utilities for 'show differences' feature */
var GPR_UTILS = GPR_UTILS || {};
GPR_UTILS.compareHelper = (function(){
    var rows = new Array(), data_collection = new Array();
    function differentData(datalist){
        if (datalist.length == 1) {
            return false
        }
        else {
            var data = datalist[0].toLowerCase().replace(/\s*/g, ''), i = 1, dllen = datalist.length;
            while (i < dllen && datalist[i].toLowerCase().replace(/\s*/g, '') == data) {
                data = datalist[i].toLowerCase().replace(/\s*/g, '');
                i++
            }
            return i < dllen
        }
    }
    return {
        /* 'row' is a reference to a <tr> DOM element 
         * 'data' is a String instance
         */
        addData: function(row, data){
            var i = 0, rowsl = rows.length;
            while (i < rowsl && rows[i] !== row) {
                i++;
            }
            /* The row is not present */
            if (i == rowsl) {
                rows.push(row);
                data_collection.push(new Array());
            }
            data_collection[i].push(data);
            return this
        },
        getRowsWithDifferentValues: function(){
            var response = new Array(), j, dclen;
            for (var i = 0, len = rows.length; i < len; i++) {
                if (differentData(data_collection[i])) {
                    response.push(rows[i])
                }
            }
            return response
        },
        clearCollection: function(){
            rows = new Array();
            data_collection = new Array();
        },
        removeData: function(collindex){
            var len = data_collection.length;
            if (len > 0 && collindex < data_collection[0].length) {
                for (var i = 0; i < len; i++) {
                    data_collection[i].splice(collindex, 1);
                }
            }
        }
    }
})();
GPR_UTILS.DOMTools = {
    addClass: function(element, value){
        if (!element.className) {
            element.className = value;
        }
        else {
            var newClassName = element.className + " " + value;
            element.className = newClassName;
        }
    },
    removeClass: function(elem, value){
        var cn = elem.className || "";
        if (cn.indexOf(value) != -1) {
            elem.className = cn.replace(value, '')
        }
    },
    hasClass: function(elem, value){
        return (elem.className || "").indexOf(value) != -1
    }
}

