/**
 * This file gets included in the header and is available throughout the site
 * Add functions that can be reused site-wide
*/


function hideSelectedPaintIcons()
{
    var icons = $$('li .selected-paint-icon');
    
    for (var i = 0; i < icons.length; i++) {
        icons[i].style.display = 'none';
    }
}


function showSelectedPaintIcon(id)
{
    if ($(id)) {
        $(id).style.display = 'inline';
    }
}


function showHideMiniBasket()
{
    var basket_items = $$('li.mini-basket-extras');
    
    if (basket_items[0].style.display != "block") {
        $('mini-count').innerHTML       = 'showing all items';
        $('mini-show-link').innerHTML   = 'show less&#133;';
    } else {
        $('mini-count').innerHTML       = 'showing 2 of ' + (basket_items.length + 2) + ' items';
        $('mini-show-link').innerHTML = 'show all&#133;';
    }
    
    for (var i = 0; i < basket_items.length; i++) {
        if (basket_items[i].style.display != "block") {
            basket_items[i].style.display = "block";
        } else {
            basket_items[i].style.display = "none";
        }
    }
}

function morphTin(src, alt, colour, duration)
{
    // tin-container-1 is behind tin-container-2. tin-container-1 is
    // updated immediately and then tin-container-2 is faded out to
    // reveal the new tin. When the fade out is finished
    // tin-container-2 is updated and restored to full opacity, ready
    // to start again.

    var img1 = $$("#tin-container-1 img")[0];
    var img2 = $$("#tin-container-2 img")[0];

    $('tin-container-1').style.backgroundImage = "url('" + src + "')";
    $("tin-container-1").style.backgroundColor = colour;
    img1.alt = alt;

    function afterFinish() {
        $('tin-container-2').style.backgroundImage = "url('" + src + "')";
        img2.alt = alt;
        
        new Effect.Opacity("tin-container-2", {from: 0, to: 1, duration: 0}); // use effect to reset opacity so it works in IE
        $("tin-container-2").style.backgroundColor = colour;
    }

    new Effect.Opacity("tin-container-2", {from: 1, to: 0, duration: duration, afterFinish: afterFinish});
}


function change_roomset(src, alt, duration)
{
    // room-container-1 is behind room-container-2. room-container-1 is
    // updated immediately and then room-container-2 is faded out to
    // reveal the new tin. When the fade out is finished
    // room-container-2 is updated and restored to full opacity, ready
    // to start again.
    
    var img1 = $$('#room-container-1 img')[0];
    var img2 = $$('#room-container-2 img')[0];

    $('room-container-1').style.backgroundImage = "url('" + src + "')";
    img1.alt = alt;
	
	//If the overlay title is present update it otherwise ignore
	if (document.getElementById("roomsets-container-overlay-title"))
		$('roomsets-container-overlay-title').update(alt);

    function afterFinish() {
        $('room-container-2').style.backgroundImage = "url('" + src + "')";
        img2.alt = alt;
        
        new Effect.Opacity("room-container-2", {from: 0, to: 1, duration: 0}); // use effect to reset opacity so it works in IE
    }

    new Effect.Opacity("room-container-2", {from: 1, to: 0, duration: duration, afterFinish: afterFinish});
}



function select_roomset (id)
{
    duration = 0.5;
    
    change_roomset(roomsets[id].src, roomsets[id].alt, duration); // morph the roomset
}

var autorotate = true;
var roomset_timer;

function rotate_roomsets(id, forward, back)
{
	var max_id = roomsets.length;

	if (forward) {
		if (autorotate) {
			if (roomset_timer)
				clearTimeout(roomset_timer);
			autorotate = false;
			anim_cnt--;
		}
		anim_cnt++;
		if (anim_cnt >= max_id) {
			anim_cnt = 0;
		}
		id = anim_cnt;
	} else if (back) {
		if (autorotate) {
			if (roomset_timer)
				clearTimeout(roomset_timer);
			autorotate = false;
			anim_cnt--;
		}
		anim_cnt--;
		if (anim_cnt < 0) {
			anim_cnt = max_id-1;
		}
		id = anim_cnt;
	}

    select_roomset(id);
	anim_cnt = id;
    
    if (autorotate) {
		anim_cnt++;
		if (anim_cnt >= max_id) {
			anim_cnt = 0;
		}
		if (roomset_timer)
			clearTimeout(roomset_timer);
		roomset_timer = setTimeout('rotate_roomsets(' + anim_cnt + ')', 5987); // timeout set to prime number - unlikely to clash with other animations
	}
}

///////  Roomset helper functions for index.php and colour_picker.php   /////////////

//Roomset button controls
function roomset_left_click(event) {
    rotate_roomsets ('', '', true);
    if (event) {
        Event.stop(event);
    }
}

function roomset_right_click(event){
    rotate_roomsets ('', true);
    if (event) {
        Event.stop(event);
    }
}

//Visability of overlay on roomset images
function show_roomset_overlay(event)
{
    //$('roomsets-container-overlay').appear({duration:0.4});
    //$('roomsets-container-overlay-background').appear({duration:0.4, to:0.5});
    $('roomsets-container-overlay').show();
    $('roomsets-container-overlay-background').show();
    if (event) {
        Event.stop(event);
    }
}


function hide_roomset_overlay(event)
{
    //$('roomsets-container-overlay').fade({duration:0.4});
    //$('roomsets-container-overlay-background').fade({duration:0.4});
    $('roomsets-container-overlay').hide();
    $('roomsets-container-overlay-background').hide();
    if (event) {
        Event.stop(event);
    }
}


/**
 * Update roomsets to match currently selected paint finish.
 *
 * @param integer   finishId    The current finish id
 * 
 *
 */
function updateRoomsets(finishId) {
    function parseResponse(transport)
    {
        roomsets = transport.responseText.evalJSON();

        //preload the roomset images
        var roomsetImg = new Image();
        roomsets.each(function(roomset) {
            roomsetImg.src = roomset.src;
        });

        // Reset the roomset timer in case there's a pending rotate_roomset() with an invalid ID.
        clearTimeout(roomset_timer);
        rotate_roomsets(0);
    }

    new Ajax.Request(
        "/lib/ajax/roomset_for_finish_data.php",
        {
            method: "get",
            parameters: "finishId=" + finishId,
            onSuccess: parseResponse
        }
    );
}

/**
 * Convert a hex RGB colour string to an HSB colour value.
 *
 * @param string hexColour The hex colour string to convert
 * 
 * @return object The HSB colour value as {hue:, saturation:, brightness:}
 */
function hex_to_hsb(hexColour)
{
    var red   = parseInt(hexColour.substr(0,2), 16) / 255;
    var green = parseInt(hexColour.substr(2,2), 16) / 255;
    var blue  = parseInt(hexColour.substr(4,2), 16) / 255;

    var x = Math.min(red, green, blue);
    var v = Math.max(red, green, blue);

    if (red == x) {
        var f = green - blue;
    } else if (green == x) {
        var f = blue - red;
    } else {
        var f = red - green;
    }

    if (red == x) {
        var i = 3;
    } else if (green == x) {
        var i = 5;
    } else {
        var i = 1;
    }

    if (x == v) {
        var hue = 0;
    } else {
        var hue = (i - f / (v - x)) * 60;
    }

    if (v == 0) {
        var saturation = 0;
    } else {
        var saturation = 100 * (v - x) / v;
    }

    var brightness = 100 * v;
    
    return {hue: Math.round(hue), saturation: Math.round(saturation), brightness: Math.round(brightness)};
}


// two globals for determining whether the finish id has changed
var previousFinishId    = 0;
var currentFinishId     = 0;


/**
 * Set up paint details in buying block
 *
 * @param string productId The paint product id to match with
 * 
 * @populates the Brand buying block via ajax
 */
function setBrandPaint(productId)
{
    function parse_response(transport)
    {
        var response = transport.responseText;
        var paintDetails = eval("(" + response + ")");
        
        if (paintDetails.name && paintDetails.manufacturer) {
        
            $("room-container-1").morph("background-color: #" + paintDetails.rgb  + ";", {duration: 0.5});
            $("room-container-2").morph("background-color: #" + paintDetails.rgb  + ";", {duration: 0.5});
            
            // highlight the currently selected paint
            hideSelectedPaintIcons();
            showSelectedPaintIcon('selected_' + cleanUpForId(paintDetails.name + paintDetails.manufacturer)); // use name + manufacturer combo rather than id - works when changing finish

            if ($('buying-block').style.display = 'none') {
                $('buying-block').show();
            }

            $$(".buying-block .paint-name")[0].innerHTML         = paintDetails.name;
            $$(".buying-block .paint-manufacturer")[0].innerHTML = "by " + paintDetails.manufacturer.replace(' and ', ' &amp; ');
        
            morphTin(paintDetails.paintPotImage, paintDetails.paintPotAlt, "#" + paintDetails.rgb, 0.5);
            
            if (!paintDetails.sample && !paintDetails.testerPot) {
                $$(".buying-block .tester-note")[0].hide();
            }
    
            if (paintDetails.testerPot) {
                $$("#test-pot .buy-box-buy a")[0].href      = "pages/basket.php?add=" + paintDetails.testerPot.id + "&quantity=1";
                $$("#test-pot .buy-box-price")[0].innerHTML = "&pound;" + paintDetails.testerPot.price;

                $('test-pot').show();
                $$(".buying-block .tester-note")[0].show();
                $$(".buying-block .tester-note")[0].innerHTML = "Buy a tester pot first to make sure you choose the perfect paint colour.";
                
                // if the customer already has the tester pot in their basket
                if (paintDetails.testerPot.has_tester) {
                    $$("#test-pot .buy-box-price")[0].hide();
                    $$("#test-pot .buy-box-buy")[0].hide();
                    $$("#test-pot .in-basket")[0].show();
                } else {
                    $$("#test-pot .buy-box-price")[0].show();
                    $$("#test-pot .buy-box-buy")[0].show();
                    $$("#test-pot .in-basket")[0].hide();
                }
            } else {
                $('test-pot').hide();
            }
            
            if (paintDetails.sample) {
                $$("#sample .buy-box-buy a")[0].href = "pages/basket.php?add=" + paintDetails.sample.id + "&quantity=1&sample=1";
                
                // if there are more than the max number of samples in the basket
                if (paintDetails.sample.samplecount >= SAMPLEFREE) {
                    $$("#sample .buy-box-price")[0].innerHTML = "&pound;" + paintDetails.sample.price;
                } else {
                    $$("#sample .buy-box-price")[0].innerHTML = "FREE";
                }
                
                $('sample').show();
                $$('.sample-notes')[0].show();
                $$(".buying-block .tester-note")[0].show();
                $$(".buying-block .tester-note")[0].innerHTML = "Buy a tester pot or painted sample first to make sure you choose the perfect paint colour.";
                
                // if the customer already has the sample in their basket
                if (paintDetails.sample.has_sample) {
                    $$("#sample .buy-box-price")[0].hide();
                    $$("#sample .buy-box-buy")[0].hide();
                    $$("#sample .in-basket")[0].show();
                } else {
                    $$("#sample .buy-box-price")[0].show();
                    $$("#sample .buy-box-buy")[0].show();
                    $$("#sample .in-basket")[0].hide();
                }
            } else {
                $('sample').hide();
                $$('.sample-notes')[0].hide();
            }
    
            buyBoxes = $$(".size-finish-block .buy-box");
            for (i = 0; i < 3; i++) {
                if (paintDetails.sizes[i]) {
                    buyBoxes[i].down(".buy-box-size").innerHTML     = paintDetails.sizes[i].size + " Litre";
                    buyBoxes[i].down(".buy-box-price").innerHTML    = "&pound;" + paintDetails.sizes[i].price;
                    buyBoxes[i].down(".buy-box-buy a").title        = "Covers up to " + paintDetails.sizes[i].coverage + "m²";
                    buyBoxes[i].down(".buy-box-buy a").href         = "pages/basket.php?add=" + paintDetails.sizes[i].id + "&quantity=1";
                    buyBoxes[i].show();
                } else {
                    buyBoxes[i].hide();
                }
            }
    
            $$(".finish-description")[0].innerHTML = paintDetails.finish.description;
            
            var selectFinish = $("finishes");
            selectFinish.options.length = 0;
            paintDetails.finishes.each(function(finish) {
                selectFinish.options[selectFinish.options.length] = new Option(finish.finishName, finish.productId);
                selectFinish.options[selectFinish.options.length -1].selected = (finish.finishId == paintDetails.finish.id);
            });
            
            currentFinishId = paintDetails.finish.id;
            
            if (currentFinishId > 0 && (currentFinishId != previousFinishId)) {
                updateRoomsets(currentFinishId);
                previousFinishId = currentFinishId;
            }
        
        } else {
            $('buying-block').hide();
        }
    }

    var applicationId = $("application") ? $("application").value : 0;

    new Ajax.Request(
        "/lib/ajax/set_paint_data.php",
        {
            method:     "get",
            parameters: "id=" + productId + "&applicationId=" + applicationId,
            onSuccess:   parse_response
        }
    );   
}


/**
 * Set up paint details in buying block
 *
 * @param string productId The paint product id to match with
 * 
 * @populates the buying block via ajax
 */
function setPaint(productId)
{
    function parse_response(transport)
    {
        var response = transport.responseText;
        var paintDetails = eval("(" + response + ")");
        
        if (paintDetails.name && paintDetails.manufacturer) {
        
            $("room-container-1").morph("background-color: #" + paintDetails.rgb  + ";", {duration: 0.5});
            $("room-container-2").morph("background-color: #" + paintDetails.rgb  + ";", {duration: 0.5});
            
            // highlight the currently selected paint
            hideSelectedPaintIcons();
            showSelectedPaintIcon('selected_' + cleanUpForId(paintDetails.name + paintDetails.manufacturer)); // use name + manufacturer combo rather than id - works when changing finish

            if ($('buying-block').style.display = 'none') {
                $('buying-block').style.display = 'block';
            }

            $$(".buying-block .paint-name")[0].innerHTML         = paintDetails.name;
            $$(".buying-block .paint-manufacturer")[0].innerHTML = "by " + paintDetails.manufacturer.replace(' and ', ' &amp; ');
        
            morphTin(paintDetails.paintPotImage, paintDetails.paintPotAlt, "#" + paintDetails.rgb, 0.5);
            
            if (!paintDetails.sample && !paintDetails.testerPot) {
                $$('#sample-block')[0].style.display = 'none';
                $$(".buying-block .colour-note")[0].innerHTML = "Please be aware your screen might not show every colour accurately.";
            } else {
                $$('#sample-block')[0].style.display = '';
            }
    
            if (paintDetails.testerPot) {
                $$("#test-pot .buy-box-buy a")[0].href      = "pages/basket.php?add=" + paintDetails.testerPot.id + "&quantity=1";
                $$("#test-pot .buy-box-price")[0].innerHTML = "&pound;" + paintDetails.testerPot.price;
                $$("#test-pot .buy-box-size")[0].innerHTML  = "Tester pot<br/>" + paintDetails.testerPot.size + "L emulsion";
                $$("#test-pot")[0].style.display            = "";
                $$(".buying-block .colour-note")[0].innerHTML = "Please be aware your screen might not show every colour accurately.<br />Buy a tester pot first to make sure you choose the perfect paint colour.";
                
                // if the customer already has the tester pot in their basket
                if (paintDetails.testerPot.has_tester) {
                    $$("#test-pot .buy-box-price")[0].style.display   = "none";
                    $$("#test-pot .buy-box-buy")[0].style.display     = "none";
                    $$("#test-pot .in-basket")[0].style.display       = "";
                } else {
                    $$("#test-pot .buy-box-price")[0].style.display   = "";
                    $$("#test-pot .buy-box-buy")[0].style.display     = "";
                    $$("#test-pot .in-basket")[0].style.display       = "none";
                }
            } else {
                $$("#test-pot")[0].style.display            = "none";
            }
            
            if (paintDetails.sample) {
                $$("#sample .buy-box-buy a")[0].href = "pages/basket.php?add=" + paintDetails.sample.id + "&quantity=1&sample=1";
                
                // if there are more than the max number of samples in the basket
                if (paintDetails.sample.samplecount >= SAMPLEFREE) {
                    $$("#sample .buy-box-price")[0].innerHTML = "&pound;" + paintDetails.sample.price;
                } else {
                    $$("#sample .buy-box-price")[0].innerHTML = "FREE";
                }
                
                // if the customer already has the sample in their basket
                if (paintDetails.sample.has_sample) {
                    $$("#sample .buy-box-price")[0].style.display   = "none";
                    $$("#sample .buy-box-buy")[0].style.display     = "none";
                    $$("#sample .in-basket")[0].style.display       = ""
                } else {
                    $$("#sample .buy-box-price")[0].style.display   = "";
                    $$("#sample .buy-box-buy")[0].style.display     = "";
                    $$("#sample .in-basket")[0].style.display       = "none"
                }
                
                $$("#sample")[0].style.display                = "";
                $$(".buying-block .colour-note")[0].innerHTML = "Please be aware your screen might not show every colour accurately.<br />Buy a tester pot or painted sample first to make sure you choose the perfect paint colour.";
            } else {
                $$("#sample")[0].style.display                = "none";
            }
    
            buyBoxes = $$(".size-finish-block .buy-box");
            for(i = 0; i < 3; i++) {
                if (paintDetails.sizes[i]) {
                    buyBoxes[i].down(".buy-box-size").innerHTML     = paintDetails.sizes[i].size + " Litre";
                    buyBoxes[i].down(".buy-box-price").innerHTML    = "&pound;" + paintDetails.sizes[i].price;
                    buyBoxes[i].down(".buy-box-coverage").innerHTML = "Covers up to " + paintDetails.sizes[i].coverage +"m&#178;";
                    buyBoxes[i].down(".buy-box-buy a").href         = "pages/basket.php?add=" + paintDetails.sizes[i].id + "&quantity=1";
                    buyBoxes[i].style.display                       = "";
                } else {
                    buyBoxes[i].style.display                       = "none";
                }
            }
    
            $$(".finish-description")[0].innerHTML = paintDetails.finish.description;
            
            var selectFinish = $("finishes");
            selectFinish.options.length = 0;
            paintDetails.finishes.each(function(finish) {
                selectFinish.options[selectFinish.options.length] = new Option(finish.finishName, finish.productId);
                selectFinish.options[selectFinish.options.length -1].selected = (finish.finishId == paintDetails.finish.id);
            });
            
            currentFinishId = paintDetails.finish.id;
            
            if (currentFinishId > 0 && (currentFinishId != previousFinishId)) {
                updateRoomsets(currentFinishId);
                previousFinishId = currentFinishId;
            }
        
        } else {
            $('buying-block').style.display = 'none';
        }
    }

    var applicationId = $("application") ? $("application").value : 0;

    new Ajax.Request(
        "/lib/ajax/set_paint_data.php",
        {
            method:     "get",
            parameters: "id=" + productId + "&applicationId=" + applicationId,
            onSuccess:   parse_response
        }
    );   
}


/**
 * Set up paint details in mini buying block
 *
 * @param string productId The paint product id to match with
 * 
 * @populates the buying block via ajax
 */
function setMiniPaint(productId, infoWinId, xOffset, yOffset, shouldToggle)
{
    function parse_response(transport)
    {
        var response = transport.responseText;
        var paintDetails = eval("(" + response + ")");
        
        var buying_block = "#buying-block-" + infoWinId;
        
        $$(buying_block + " .paint-name")[0].innerHTML         = paintDetails.name;
        $$(buying_block + " .paint-manufacturer")[0].innerHTML = 'by ' + paintDetails.manufacturer.replace(' and ', ' &amp; ');
        
        $$(buying_block + " .tin-container")[0].style.backgroundColor = "#" + paintDetails.rgb;
        $$(buying_block + " .tin-container")[0].style.backgroundImage = "url('" + paintDetails.paintPotImage + "')";
        $$(buying_block + " .tin-container img")[0].alt = paintDetails.paintPotAlt;

        if (!paintDetails.sample && !paintDetails.testerPot) {
            $$(buying_block + " .colour-note")[0].innerHTML = "Please be aware your screen might not show every colour accurately.";
        }

        if (paintDetails.testerPot) {
            $$(buying_block + " .test-pot .buy-box-buy a")[0].href      = "pages/basket.php?add=" + paintDetails.testerPot.id + "&quantity=1";
            $$(buying_block + " .test-pot .buy-box-price")[0].innerHTML = "&pound;" + paintDetails.testerPot.price;
            $$(buying_block + " .test-pot")[0].style.display            = "";
            $$(buying_block + " .colour-note")[0].innerHTML             = "Please be aware your screen might not show every colour accurately. Buy a tester pot first to make sure you choose the perfect paint colour.";
            
            // if the customer already has the tester pot in their basket
            if (paintDetails.testerPot.has_tester) {
                $$(buying_block + " .test-pot .buy-box-price")[0].style.display   = "none";
                $$(buying_block + " .test-pot .buy-box-buy")[0].style.display     = "none";
                $$(buying_block + " .test-pot .in-basket")[0].style.display       = ""
            } else {
                $$(buying_block + " .test-pot .buy-box-price")[0].style.display   = "";
                $$(buying_block + " .test-pot .buy-box-buy")[0].style.display     = "";
                $$(buying_block + " .test-pot .in-basket")[0].style.display       = "none"
            }
        } else {
            $$(buying_block + " .test-pot")[0].style.display = "none";
        }
        
        if (paintDetails.sample) {
            $$(buying_block + " .sample .buy-box-buy a")[0].href = "pages/basket.php?add=" + paintDetails.sample.id + "&quantity=1&sample=1";
            
            // if there are more than the max number of samples in the basket
            if (paintDetails.sample.samplecount >= SAMPLEFREE) {
                $$(buying_block + " .sample .buy-box-price")[0].innerHTML = "&pound;" + paintDetails.sample.price;
            } else {
                $$(buying_block + " .sample .buy-box-price")[0].innerHTML = "FREE";
            }
            
            // if the customer already has the sample in their basket
            if (paintDetails.sample.has_sample) {
                $$(buying_block + " .sample .buy-box-price")[0].style.display   = "none";
                $$(buying_block + " .sample .buy-box-buy")[0].style.display     = "none";
                $$(buying_block + " .sample .in-basket")[0].style.display       = ""
            } else {
                $$(buying_block + " .sample .buy-box-price")[0].style.display   = "";
                $$(buying_block + " .sample .buy-box-buy")[0].style.display     = "";
                $$(buying_block + " .sample .in-basket")[0].style.display       = "none"
            }
            
            $$(buying_block + " .sample")[0].style.display  = "block";
            $$(buying_block + " .colour-note")[0].innerHTML = "Please be aware your screen might not show every colour accurately. Buy a tester pot or painted sample first to make sure you choose the perfect paint colour.";
        } else {
            $$(buying_block + " .sample")[0].style.display  = "none";
        }

        var buyBoxes = $$(buying_block + " .buying-boxes .buy-box");
        for(i = 0; i < 3; i++) {
            if (paintDetails.sizes[i]) {
                buyBoxes[i].down(".buy-box-size").innerHTML     = paintDetails.sizes[i].size + " Litre";
                buyBoxes[i].down(".buy-box-price").innerHTML    = "&pound;" + paintDetails.sizes[i].price;
                buyBoxes[i].down(".buy-box-buy a").href         = "pages/basket.php?add=" + paintDetails.sizes[i].id + "&quantity=1";
                buyBoxes[i].style.display                       = "";
            } else {
                buyBoxes[i].style.display                       = "none";
            }
        }

        $$(buying_block + " .finish-description")[0].innerHTML = paintDetails.finish.description;
        
        var selectFinish = $$(buying_block + " .finishes")[0];
        selectFinish.options.length = 0;
        //selectFinish.onMouseOut     = 'Event.stop(event)'; // prevent this event bubbling up through DOM and hiding info win
        paintDetails.finishes.each(function(finish) {
            selectFinish.options[selectFinish.options.length]                   = new Option(finish.finishName, finish.productId);
            selectFinish.options[selectFinish.options.length -1].selected       = (finish.finishId == paintDetails.finish.id);
            selectFinish.options[selectFinish.options.length -1].onClick        = 'Event.stop(event)'; // prevent this event bubbling up through DOM and hiding info win
            //selectFinish.options[selectFinish.options.length -1].onMouseOut     = 'Event.stop(event)'; // prevent this event bubbling up through DOM and hiding info win
        });
        
        if (shouldToggle) {
            toggle_info_win('paint_info_' + infoWinId, xOffset, yOffset);
        } else {
            show_info_win('paint_info_' + infoWinId, xOffset, yOffset);
        }
    }

    var applicationId = $("application") ? $("application").value : 0; // not used but still needed

    new Ajax.Request(
        "/lib/ajax/set_paint_data.php",
        {
            method:     "get",
            parameters: "id=" + productId + "&applicationId=" + applicationId,
            onSuccess:   parse_response
        }
    );
}


/** Tests to see if a mini buying window is already open
 *
 *  @param  string  productId   The product id to display
 *  @param  string  infoWinId   The info win id to display
 *  @param  integer xOffset     The horizontal offset in pixels from the element's parent
 *  @param  integer yOffset     The vertical offset in pixels from the element's parent
 *
 *  if not already showing, sets paint details (used with mouseover/mouseout functionality - now defunct)
 */
function setMiniBuying(productId, infoWinId, xOffset, yOffset)
{    
    if ($('paint_info_' + infoWinId).style.display != 'inline') { // if the desired window is not already displaying
        
        if (typeof(setMiniPaint_timeout) != 'undefined') { // cancel the previous timeout if it exists
            clearTimeout(setMiniPaint_timeout);
        }
        
        setMiniPaint_timeout = setTimeout('setMiniPaint(' + productId + ', ' + infoWinId + ', ' + xOffset + ', ' + yOffset + ')', 500); // add short delay to call so that info wins don't open while scrolling across them
    }
}

var setMiniPaint_timeout = 0; // for storing timeout calls


/** Cleans up strings for use as in xhtml ids
 *
 *  @param string $string
 *
 *  @return converted string
 */
function cleanUpForId(str)
{
    str = str.replace(/\\/g, '');
    str = str.replace(/'/g, '');
    str = str.replace(/"/g, '');
    str = str.replace(/&/g, '');
    str = str.replace(/%/g, '');
    str = str.replace(/ /g, '');
    str = str.toLowerCase();
    
    return str;
}


/** Checks whether mouseover/mouseout is from calling element or children
 *  This 'cleans' up flickering etc
 *
 *  Determines whether the event is the equivalent of the microsoft
 *  mouseleave or mouseenter events (cross browser compatible)
 *  Ref: http://dynamic-tools.net/toolbox/isMouseLeaveOrEnter/
 *
 *  @param e        Event
 *  @param handler  Event handler
 *
 *  @return false, handler or null
 */
function isMouseLeaveOrEnter(e, handler)
{		
    if (e.type != 'mouseout' && e.type != 'mouseover') {
        return false;
    }

    var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;

    while (reltg && reltg != handler) {
        reltg = reltg.parentNode;
    }

    return (reltg != handler);
}
