
// This is a routine to check if the value in the input component is a
// multiple of some passed in integer.
// If it isn't an alert is raised and the value is changed to the next multiple
//
// <input name="quantity" type="text" value="12" size="6" maxlength="6"
//       onChange="checkValueIsMultiple(document.blowup.quantity, 12)" />

function checkValueIsMultiple(input, multiple, maximum)
{
    if (! isNaN(parseInt(input.value, 10)) )
    {
        if (parseInt(input.value, 10) > 0 &&
            parseInt(multiple, 10) > 0)
        {
            input.value = parseInt(input.value, 10);
            var remainder = parseInt(input.value, 10) % parseInt(multiple, 10);
            if ( remainder > 0 )
            {
                var newvalue = parseInt(input.value, 10) + parseInt(multiple, 10) - parseInt(remainder, 10);
                // has to occur before alert so that it changes before a submit event
                if ( isNaN(maximum) || newvalue <= maximum )
                {
                    input.value = newvalue;
                    alert("This item's quantity must be in multiples of " + multiple +
                        ". Increasing to next multiple " + newvalue + ".");
                }
                else
                {
                    newvalue = parseInt(input.value, 10) - parseInt(remainder, 10);
                    input.value = newvalue;
                    alert("This item's quantity must be in multiples of " + multiple +
                        " and a quantity that is less than " + (maximum + 1) +
                        ". Decreasing to last multiple " + newvalue + ".");
                }
            }
        }
    }
}


// Pass the following to JS_question itself, via the onclick
// attribute for the tag

// question    : the question to be asked, for a yes or no answer
// destination : set object.href='$destination' if the answer is yes

function confirmRedirect(question,destination)
{
	if (confirm(question))
		location.replace(destination);

	return false;
}

/* confirmRedirect_wait

Redirect, but also change the label of the passed element to "Please
wait".

 */
function confirmRedirect_wait(question,destination,elt) {
    if(confirm(question)) {
        elt.value = 'Please wait';
        location.replace(destination);
    }
    
    return false;
}

// NO XSLT parameters required:
// Rather, pass the following to the spin() function itself, via the href attribute
// for an <a> tag containing the SUBTRACT or ADD button:
// <a href="JavaScript: spin(document.form.inputname, 10, -1);"><img src="SUBTRACT.gif" border=0></a>
// <a href="JavaScript: spin(document.form.inputname, 10, +1, 1000);"><img src="ADD.gif" border=0></a>

function spinButton(input, increment, sign, maximum)
{
    if ( sign > 0 && ( input.value==null || input.value=="" ) )
    {
        input.value = 0;
    }
    if ( maximum == null || maximum == "" )
    {
        maximum = "999999999";
    }
	if ( increment <= maximum &&
         (increment &&
          ! isNaN(parseInt(input.value, 10))) )
	{
            input.value = parseInt(input.value, 10);
		if (parseInt(input.value, 10) < increment) {
			if (sign > 0) {
                input.value = increment;
            }
            else {
                input.value = 0;
            }
		} else {
                    var remainder = parseInt(input.value, 10) % increment;
            if ( sign > 0 )
            {
                if ( (parseInt(input.value, 10) + increment - remainder) <=
                        maximum )
                {
                    input.value = parseInt(input.value, 10) + increment - remainder;
                }
            }
            else if ( remainder )
            {
                input.value = parseInt(input.value, 10) - remainder;
            }
            else
            {
                input.value = parseInt(input.value, 10) - increment;
            }
		}
		if (parseInt(input.value, 10) < 1) input.value = "";
	}
    //else { alert("not valid"); }
}

// function for appending those little up and down arrow buttons after
// quantity fields. It is in a script to avoid printing it on non-javascript
// browsers and to save space in the html output
// call like:
// <script>
// <!--
// spinArrows( 'document.catalogue_search.quantity_10000506', 12, 1000 )
// //-->
// </script>
function spinArrows( input, integer, maximum )
{
    document.write('<div class="qty_arrows">');

    if ( maximum || maximum == 0 )
    {
        document.write('<a href="JavaScript: spinButton(' + input + ', ' +
                        integer + ', 1, ' + maximum + ')">');
    }
    else
    {
        document.write('<a href="JavaScript: spinButton(' + input + ', ' +
                        integer + ', 1)">');
    }
	document.write('<img src="media/images/new/arrow-up.gif" alt="Increase Quantity" \/>');
	document.write('</a>');
	document.write('<a href=\"JavaScript: spinButton(' + input + ', ' +
					integer + ', -1)\"\>');
	document.write('<img src="media/images/new/arrow-down.gif" alt="Decrease Quantity" \/></a>');
    
    document.write('</div>');
}

function setCookie(name,value,days) {
	var date = new Date();
	date.setTime(date.getTime()+(days*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
	document.cookie = name + '=' + value + expires + '; path=/';
}

// Functions for selecting/deselecting all checkboxes in a form.
// Typically used with the tables generated using TableGenerator that has a delete
// checkbox related to each row.

function local_getElementById ( id )
{
    var ele;
        //safe function to hide an element with a specified id
        if (document.getElementById) { // DOM3 = IE5, NS6
                ele = document.getElementById(id);
        }
        else {
                if (document.layers) { // Netscape 4
                        ele = document.id;
                }
                else { // IE 4
                        ele = document.all.id;
                }
        }
    return ele;
}

function selectAll( formid )
{
    var form = local_getElementById(formid);

    for(var i=0; i<form.elements.length; i++) {
        if(form.elements[i].type == "checkbox") {
            //further restrict by name. Checkbox needs to have the string 'del' in it.
            if (form.elements[i].name.search(/del/) >= 0) {
                form.elements[i].checked=true;
            }
        }
    }
}

function unselectAll( formid )
{
    var form = local_getElementById(formid);

    for(var i=0; i<form.elements.length; i++) {
        if(form.elements[i].type == "checkbox") {
            //further restrict by name. Checkbox needs to have the string 'del' in it.
            if (form.elements[i].name.search(/del/) >= 0) {
                form.elements[i].checked=false;
            }
        }
    }
}

function Reset( obj ) {
    obj.value = "";
}

function SetIfBlank( obj, val ) {
    if (obj.value == '') {
        obj.value = val;
    }
}


function hideLayer(element) {
    element.style.display = 'none';
}

function showLayer(element) {
    element.style.display = 'block';
}

// Function to show/hide a given layer.
function toggleLayer(element) {
    element.style.display = (element.display == '' || element.style.display == 'block' ) ? 'none' : 'block';
}

function setDisplay(ident, disp_type) {
    var elt = getElement(ident);
    elt.style.display = disp_type;
}

function getElement(layerId) {
    var element;
    // standard browsers.
    if (document.getElementById) {
        element = document.getElementById(layerId);
    }
    // old MSIE browsers.
    else if (document.all) {
        element = document.all[layerId];
    }
    // NN4
    else if (document.layers) {
        element = document.layers[layerId];
    }
    return element;
}




function editlinenote(lineid) {
    document.getElementById("linenote-"+lineid).className = "hidden";
    document.getElementById("editlinenote-"+lineid).className = "visible";
    document.getElementById("editlinenotereftext-"+lineid).className = "visible";
    var input = document.getElementById("editlinenoteinput-"+lineid);
    input.readOnly = false;
    input.focus();
    return false;
}

function uneditlinenote(input, lineid, event) {
    if (event.keyCode == 27) {
        // Escape key was pressed
        input.value = input.defaultValue;
        input.readOnly = true;
        document.getElementById("linenote-"+lineid).className = "visible";
        document.getElementById("editlinenote-"+lineid).className = "hidden";
        document.getElementById("editlinenotereftext-"+lineid).className = "hidden";
        document.getElementById("linenotetext-"+lineid).focus();
        return false;
    } else {
        // Do nothing, let the keypress pass through.
        return true;
    }
}

//function check_quantities() {
//    var value = true;
//    
//    [% FOREACH item IN widget.order.items %]
//        if (document.view_current_order.quantity_[% item.itemid %].value > [% item.quantity %])
//            value = false;
//    [% END %]
//        
//    if (!value)
//        return confirm("Order will be resubmitted if quantities are increased. Do you like to proceed?");
//}
var submit_times = { };
var delay_interval = 15000; /* In msec */

function limitSubmit_reset( ) {
    /* This flushes the existing recorded submit times */
    submit_times = new Object();
}

function limitSubmit_attachActions( ) {
    var i = 0;
    var d = new Date();
    for( i = 0; i < document.forms.length; i++ ) {
        limitSubmit_attachFormActions( document.forms[i] );
    }
}

function limitSubmit_attachFormActions( target_form ) {
    var inputs = target_form.elements;
    var i = 0;

    target_form.onsubmit = function() {
        var rv = limitSubmit(target_form);
        return rv;
    };
}

function limitOnName( target_name ) {
    var d = new Date();
    var time_now = d.getTime();

    var last_submit = submit_times[target_name];
    submit_times[target_name] = time_now;
    if( last_submit ) {
        if( last_submit > ( time_now - delay_interval ) ) {
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
}

function limitSubmit( target_form ) {
    var d = new Date();
    var form_name = target_form.name;

    return limitOnName(form_name);
}

function limitButton( target_form, button ) {
    var form_name = target_form.name;
    var button_name = button.name;

    var submit_name = form_name + '/' + button_name;
    return limitOnName(submit_name);
}

//
// Toggle tabs on a CDS (CNET Data Source) product blowup
//
function toggleTab(oShow)
{
    // Get the NXTabs wrapper element
    var NXTabs = document.getElementById('NXTabs');

    // Go through the NXTabs, disabling each NXTab
	if (NXTabs.childNodes.length) {
		for(var i = 0; i < NXTabs.childNodes.length; i++)
		{
			if (NXTabs.childNodes[i].id.match("NXTab")) {
				NXTabs.childNodes[i].className = 'NXTabOff';
			}
		}
	}

    // Now do the same for NXTabsContent wrapper element
    var NXContents = document.getElementById('NXTabsContent');

    // Go through the NXTabsContent, disabling all of its NXTabsData elements
    for(var i = 0; i < NXContents.childNodes.length; i++)
	{
        if (NXContents.childNodes[i].className == "NXTabsData") {
            NXContents.childNodes[i].style.display = 'none';
        }
    }

    // enable the selected NXTab
    var selected_head = 'NXTab' + oShow;
    document.getElementById(selected_head).className = "NXTabOn";

	// enable the matching NXTabData
    var selected_content = 'NXTabData' + oShow;
    document.getElementById(selected_content).style.display = "inline";
}



//
// browser window size/position functions
//
function pageWidth() 
   {
   return window.innerWidth != null ? window.innerWidth : 
      document.documentElement && document.documentElement.clientWidth ? 
         document.documentElement.clientWidth : document.body != null ? 
            document.body.clientWidth : null;
   } 

function pageHeight() 
   {
   return window.innerHeight != null ? window.innerHeight : 
      document.documentElement && document.documentElement.clientHeight ? 
         document.documentElement.clientHeight : document.body != null ? 
            document.body.clientHeight : null;
   } 

function posLeft() 
   {
   return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :
      document.documentElement && document.documentElement.scrollLeft ? 
         document.documentElement.scrollLeft : document.body.scrollLeft ? 
            document.body.scrollLeft : 0;
   } 

function posTop() 
   {
   return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : 
      document.documentElement && document.documentElement.scrollTop ? 
         document.documentElement.scrollTop : document.body.scrollTop ? 
            document.body.scrollTop : 0;
   } 

function posRight() 
   {
   return posLeft() + pageWidth();
   } 

function posBottom() 
   {
   return posTop() + pageHeight();
   }


//
// Make the Pop-Up Div visible (which includes positioning it appropriately).
//
function setPopUpDivVisible(ev,obj,flag)
{
    obj = document.getElementById(obj);
    var e=ev ? ev : window.event;
    var l = posLeft();          // window position Left
    var r = posRight();         // window position Right
    var t = posTop();           // window position Top
    var b = posBottom();        // window position Bottom
    var x = e.clientX + 22;     // mouse click Xposition
    var y = e.clientY + t + 22; // mouse-click Yposition
    var w = obj.offsetWidth;    // pop up div width
    var h = obj.offsetHeight;   // pop up div height
    if (x < l) {                // will div be off the left edge?
        x = l;                      // yep, move it to the right
    }
    if ((x + w) > r) {          // will div be off the right edge?
        x = r - w - 20;             // yep, move it to the left
    }
    if (y < t) {                // will div be off the top?
        y = t;                      // yep, move it down
    }
    if ((y + h) > b) {          // will div be off the bottom?
        y = b - h;                  // yep, move it up
    }
    obj.style.left = x + 'px';  
    obj.style.top = y + 'px';   
    obj.style.zIndex = 50;      // put div on top of merch_fadeout
    if (flag) {                 // make it appear/disappear
        obj.style.visibility = 'visible';
        // This is to track how many times the icons are clicked on
        urchinTracker('/nxstats/popup_viewed/');
    } else {
        obj.style.visibility = 'hidden';
    }

}

