// $Id: common.js,v 1.50 2005/08/12 00:05:40 simon Exp $

// Retrieve a client cookie
function jsGetCookie(name)
{
    cookieList = new String(document.cookie);
    cookieArray = cookieList.split('; ');

    for (i = 0; i < cookieArray.length; i++)
    {
        keyval = cookieArray[i].split("=");
        if (keyval[0] == name)
            return (keyval[1]);
    }
    return ('');
}

// Create a client cookie
function jsSetCookie(name, val, expires, path, domain)
{
    cookie = name + "=" + val;

    if (expires)
        cookie += ";expires=" + expires;

    if (path)
        cookie += ";path=" + path;

    if (domain)
        cookie += ";domain=" + domain;

    document.cookie = cookie;
}

// Version of getAttribute that works for both Mozilla and IE.
function jsGetAttribute(obj, name)
{
    aNode = null;
    if (obj.attributes)
        aNode = obj.attributes.getNamedItem(name);

    if (aNode)
        return (aNode.nodeValue);
    else
        return (null);
}

// Returns the Element with the specified id
function jsGetElementById(id)
{
    return (document.getElementById(id));
}

// Returns an array of all Elements descended from the specified root node.
function jsGetElements(root)
{
    var children, child, res;

    if (!root)
        // A root Element wasn't provided, so start at the top.
        children = document.childNodes;
    else
        // Otherwise, search the children of the provided root.
        children = root.childNodes;

    res = new Array();
    for (var i = 0; i < children.length; i++)
    {
        child = children[i];

        // Only return Elements
        if (child.nodeType === 1)
            res[res.length] = child;

        // Recurse to this child's children.
        res = res.concat(jsGetElements(child));
    }
    return (res);
}

// Returns an array of Elements that share the same property value.
function jsGetElementsByProperty(prop, val, root)
{
    all = jsGetElements(root);

    res = new Array();
    for (var i = 0; i < all.length; i++)
    {
        if (String(jsGetAttribute(all[i], prop)).match(val))
            res[res.length] = all[i];
    }
    return (res);
}

// Return an array of Elements that share the same class
function jsGetElementsByClass(name, root)
{
    return (jsGetElementsByProperty('class', name, root));
}

// This function sets the specified property of the given object
function jsSetProperty(prop, val, obj)
{
    if (obj != null) // If the id exists...
    {
        if (val != null)
            eval('obj.' + prop + '="' + val + '"');
        else
            obj.removeAttribute(prop);
    }
}

// Set the specified property of all tags of the specified class.
function jsSetPropertyByClass(prop, val, name)
{
    var elements = jsGetElementsByClass(name);
    for (var i = 0; i < elements.length; i++)
        jsSetProperty(prop, val, elements[i]);
}

// This function 'hides' the specified object
function jsHideObject(obj)
{
    jsSetProperty('style.display', 'none', obj);
}

// This function 'un-hides' the specified object
function jsShowObject(obj)
{
    if (obj == null)
        return;
    if (obj.tagName == 'SPAN')
        jsSetProperty('style.display', 'inline', obj);
    else
        jsSetProperty('style.display', 'block', obj);
}

// Switch the visibility state of the given object.
function jsToggleObject(obj)
{
    if (obj == null)
        return;
    if (obj.style.display == "none")
        jsShowObject(obj);
    else
        jsHideObject(obj);
}

// Hide or show the tag with the specified ID
function jsSetObjectVisibilitytById(id, show)
{
    if (show)
        jsShowObject(jsGetElementById(id));
    else
        jsHideObject(jsGetElementById(id));
}

// Hide the tag with the specified ID
function jsHideObjectById(id)
{
    jsHideObject(jsGetElementById(id));
}

// Un-hide the tag with the specified ID
function jsShowObjectById(id)
{
    jsShowObject(jsGetElementById(id));
}

// Switch the visibility state of the object with the given ID
function jsToggleObjectById(id)
{
    jsToggleObject(jsGetElementById(id));
}

// Hide or show the tag with the specified class
function jsSetObjectVisibilitytByClass(name, show)
{
    if (show)
        jsShowObjectsByClass(name);
    else
        jsHideObjectsByClass(name);
}

// Hide all of the tags in the specified class
function jsHideObjectsByClass(name)
{
    jsSetPropertyByClass('style.display', 'none', name);
}

// Show all of the tags in the specified class
function jsShowObjectsByClass(name)
{
    var elements = jsGetElementsByClass(name);
    for (var i = 0; i < elements.length; i++)
        jsShowObject(elements[i]);
}

// Show only the member of "className" with the specified id
// Hide all other members.
function jsShowClassMember(id, className)
{
    jsHideObjectsByClass(className);
    jsShowObjectById(id);
}

// Shows or hides an object based on a checkbox or radio button's state.
function jsShowObjectOnCheck(id, checkbox)
{
    if (checkbox.checked)
        jsShowObject(jsGetElementById(id));
    else
        jsHideObject(jsGetElementById(id));
}

// Shows or hides a class of objects based on a
// checkbox or radio button's state.
function jsShowClassOnCheck(className, checkbox)
{
    if (checkbox.checked)
        jsShowObjectsByClass(className);
    else
        jsHideObjectsByClass(className);
}

// precaches an image and returns the new Image object
function jsPrecacheImage(src)
{
    image = new Image();
    image.src = src;

    return(image);
}

function selectItem( form, name, itemIndex )
{
    inputs = jsGetElementById( form ).elements;
    index = 0;
    i = 0;
    found = false;
    do
    {
        if( inputs[i].name == name )
        {
            if( index == itemIndex )
            {
                inputs[ index ].checked = true;
                found = true;
            }
            index++;
        }
        i++;
    } while ( (index<inputs.length) && (!found) );
}

function addSessionPost(form, name, value)
{
    session_post = document.createElement( "INPUT" );
    session_post.setAttribute( "type","hidden" );
    session_post.setAttribute( "name","sessionPost[" + name + "]" );
    session_post.setAttribute( "value",value );
    form.appendChild( session_post );
}

function checkType( value )
{
    form = jsGetElementById( "contentForm" );
    addSessionPost(form, "type", value);
    jsGetElementById( "task" ).value = "none";
    if(form.cName.value != "") addSessionPost(form, "name", form.cName.value);
    if(form.cDesc.value != "") addSessionPost(form, "description", form.cDesc.value);

    // redirect to the create tab...
    form.action = "index.php?page=autoTabPage.php&item=content&content_tab=create";
    form.target = "_top";

    form.submit();
}

function checkTemplateType(type)
{
    jsShowClassMember("cma_create_" + type + "_container", "cma_page_create_containers");
    jsHideObjectsByClass("cma_" + ((type == "base") ? "compound" : "base") + "_template");
    jsShowObjectsByClass("cma_" + type + "_template");
}

function editContent( form, content_id )
{
    // redirect to the create tab...
    form.action = "index.php?page=autoTabPage.php&item=content&content_tab=edit";
    form.target = "_top";

    // append sessionPost...
    addSessionPost(form, "content_id", content_id);

    form.submit();
}

function editSite( form, site_id )
{
    // redirect to the create tab...
    form.action = "index.php?page=autoTabPage.php&item=sites&sites_tab=create/edit";
    form.target = "_top";

    // append sessionPost...
    addSessionPost(form, "siteEditId", site_id);

    form.submit();
}

function loadTemplate( template_id )
{
    form = jsGetElementById( "contentForm" );

    // append sessionPost...
    addSessionPost(form, "template_id", template_id);
    checkType( form.cType.value );
}

function editTemplate(form, template_id, type)
{
    // redirect to the create tab...
    form.action = "index.php?page=autoTabPage.php&item=templates&templates_tab=create/edit";
    form.target = "_top";

    // append sessionPost...
    addSessionPost(form, "template_id", template_id);
    addSessionPost(form, "type", type);
}

function returnToBrowse()
{
    form = jsGetElementById( "contentForm" );

    // redirect to the create tab...
    form.action = "index.php?page=autoTabPage.php&item=content&content_tab=browse";
    form.target = "_top";
}

function returnToEdit(content_id)
{
    form = jsGetElementById( "contentForm" );

    // redirect to the create tab...
    form.action = "index.php?page=autoTabPage.php&item=content&content_tab=edit";
    form.target = "_top";

    // append sessionPost...
    addSessionPost(form, "content_id", content_id);

    form.submit();
}

function returnToTemplateList(form, type)
{
    // redirect to the template tab of 'type'
    form.action = "index.php?page=autoTabPage.php&item=templates&templates_tab=" + type;
    form.target = "_top";
}

function selectTemplate( template_id )
{
    form = jsGetElementById( "contentForm" );

    // append sessionPost...
    addSessionPost(form, "template_id", template_id);
}

function saveContent( form )
{
    re = /\/(catalogue|site)Files\/[^\/]*/g;

    // append sessionPost...
    addSessionPost(form, "type", form.cType.value);
    addSessionPost(form, "name", form.cName.value);
    addSessionPost(form, "description", form.cDesc.value);
    switch(form.cType.value)
    {
        case 1: // Normal
            addSessionPost(form, "content", form.contentField.value.replace(re, ""));
            break;
        case 2: // Widget
            break;
        case 3: // Block
            addSessionPost(form, "template", form.template.value);
            break;
    }

    // redirect to the create tab...
    form.action = "index.php?page=autoTabPage.php&item=content&content_tab=create";
    form.target = "_top";

    return true;
}

function previewPage(element, id)
{
    if (element.tagName != "FORM")
        form = element.form;

    addSessionPost(form, "previewPageId", id);

    form.action = "/index.php?page=autoTabPage.php&item=pages&pages_tab=layout";
    form.target = "_top";
}

function enableEditMode(enabled)
{
    if (enabled)
    {
        jsShowObjectsByClass('cma_slot_toolbar');
        jsShowObjectsByClass('cma_empty_slot');
    }
    else
    {
        jsHideObjectsByClass('cma_slot_toolbar');
        jsHideObjectsByClass('cma_empty_slot');
    }
}

function redirectToPreview(pageId)
{
    document.open();
    document.write('<form id="redirect" action="" method="post">');
    document.write('</form>');
    document.close();

    form = jsGetElementById("redirect");

    previewPage(form, pageId);

    form.submit();
}

function createPageGroup(element, parentId)
{
    addSessionPost(element.form, "pageGroupParentId", parentId);
    addSessionPost(element.form, "createType", "createGroup");

    element.form.action = "/index.php?page=autoTabPage.php&item=pages&pages_tab=create/edit";
    element.form.target = "_top";
}

function editPageGroup(element, id)
{
    addSessionPost(element.form, "pageGroupId", id);
    addSessionPost(element.form, "createType", "createGroup");

    element.form.action = "/index.php?page=autoTabPage.php&item=pages&pages_tab=create/edit";
    element.form.target = "_top";
}

function deletePageGroup(element)
{
    if (confirmAction('Are you sure you want to delete this page group?'))
    {
        if (confirmAction('Click OK to delete subgroups and pages as well.'))
            element.form.elements.namedItem("groupDeleteCascade").value = "yes";
        else
            element.form.elements.namedItem("groupDeleteCascade").value = "no";

        return (true);
    }
    return (false);
}

function createPage(element, parentGroupId)
{
    addSessionPost(element.form, "pageGroupParentId", parentGroupId);
    addSessionPost(element.form, "createType", "createPage");

    element.form.action = "/index.php?page=autoTabPage.php&item=pages&pages_tab=create/edit";
    element.form.target = "_top";
}

function editPage(element, pageId)
{
    addSessionPost(element.form, "pageId", pageId);
    addSessionPost(element.form, "createType", "createPage");

    element.form.action = "/index.php?page=autoTabPage.php&item=pages&pages_tab=create/edit";
    element.form.target = "_top";
}

function confirmAction(prompt)
{
    if (!prompt)
        prompt = "Are you sure you want to continue?";

    response = confirm(prompt);
    if(response)
        return true;
    else
        return false;
}

function toggleCell(div)
{
    alert('here');
    div.style.backgroundColor.value = (div.style.backgroundColor.value =='#ffffff') ? "#efefef" : "#ffffff";
}

function expandNode(nodeId, bodyObj)
{
    if (!bodyObj)
        bodyObj = jsGetElementById(nodeId + "_body");
    imgObj = jsGetElementById(nodeId + "_img");

    bodyObj.style.display = "block";
    imgObj.src = imgObj.src.replace("right", "down");
}

function collapseNode(nodeId, bodyObj)
{
    if (!bodyObj)
        bodyObj = jsGetElementById(nodeId + "_body");
    imgObj = jsGetElementById(nodeId + "_img");

    bodyObj.style.display = "none";
    imgObj.src = imgObj.src.replace("down", "right");
}

function toggleNode(nodeId)
{
    bodyObj = jsGetElementById(nodeId + "_body");
    if (bodyObj.style.display == "block")
        collapseNode(nodeId, bodyObj);
    else
        expandNode(nodeId, bodyObj);
}

function enableControl(controlId, enabled)
{
    if (enabled == true)
        jsGetElementById(controlId).removeAttribute('disabled');
    else
        jsGetElementById(controlId).setAttribute('disabled', 'true');
}

function storeClientTzOffset()
{
    now = new Date();
    tzOffset = - now.getTimezoneOffset();
    jsSetCookie("TZ_OFFSET_M", tzOffset);
}

function checkRadio(value)
{
    inputs = document.getElementsByTagName("input");
    for(i=0; i<inputs.length; i++)
    {
        if((inputs[i].type == "radio") && (inputs[i].value == value))
            inputs[i].checked = true;
    }
}

function swapGroup(index, id, clearExternal)
{
    pageOptions = jsGetElementById("i_link[" + index + "]");

    // remove old options
    for(i=pageOptions.length-1; i>=0; i--)
        pageOptions.removeChild(pageOptions.options[i]);

    // append new options
    newOptions = eval("pages_" + id);
    for(i=0; i<newOptions.length; i++)
    {
        values = newOptions[i].split("|");
        pageOptions.appendChild(document.createElement("option"));
        pageOptions.options[pageOptions.options.length - 1].value = values[0];
        pageOptions.options[pageOptions.options.length - 1].text = values[1];
    }

    if(clearExternal)
        jsGetElementById("x_link[" + index + "]").value = "";
}

function loadGroupPages()
{
    index = 0;
    while(jsGetElementById("group[" + index + "]"))
    {
        swapGroup(index, jsGetElementById("group[" + index + "]").value, 0);
        index++;
    }
}

function loadLocatorCodes()
{
    cat = jsGetElementById("category");
    sub = jsGetElementById("subcategory");
    locatorOptions = jsGetElementById("locator");
    newOptions = new Array();
    cats = new Array();
    subs = new Array();
    sels = new Array();

    // get currently selected locator codes
    for(i=0; i<locatorOptions.length; i++)
    {
        if(locatorOptions.options[i].selected)
            sels[sels.length] = locatorOptions.options[i].value;
    }

    // remove old codes
    for(i=locatorOptions.length-1; i>=0; i--)
        locatorOptions.removeChild(locatorOptions.options[i]);

    // append new options
    for(x=0; x<cat.options.length; x++)
    {
        if(cat.options[x].selected)
            cats[cats.length] = cat.options[x].value;
    }
    for(y=0; y<sub.options.length; y++)
    {
        if(sub.options[y].selected)
            subs[subs.length] = sub.options[y].value;
    }

    for(x=0; x<cats.length; x++)
    {
        codeset = "codes_" + cats[x];
        if(eval("typeof " + codeset) != 'undefined')
            newOptions = appendOptions(newOptions, eval(codeset));

        for(y=0; y<subs.length; y++)
        {
            subcodeset = codeset + "_" + subs[y];
            if(eval("typeof " + subcodeset) != 'undefined')
                newOptions = appendOptions(newOptions, eval(subcodeset));
        }
    }
    newOptions.sort();

    for(i=0; i<newOptions.length; i++)
    {
        locatorOptions.add(document.createElement("option"));
        locatorOptions.options[locatorOptions.options.length - 1].value = newOptions[i];
        locatorOptions.options[locatorOptions.options.length - 1].text = newOptions[i];
        locatorOptions.options[locatorOptions.options.length - 1].selected = inArray(sels, newOptions[i]);
    }
}

function selectOptions(select, options)
{
    selectObj = jsGetElementById(select);

    if(options != "")
    {
        selected = options.split(",");
        for(i=0; i<selectObj.length; i++)
        {
            if(inArray(selected, selectObj.options[i].value))
                selectObj.options[i].selected = true;
        }
    }
}

function appendOptions(options, set)
{
    addOptions = set.split(",");
    for(i=0; i<addOptions.length; i++)
    {
        if(! inArray(options, addOptions[i]))
            options.splice(options.length, 0, addOptions[i]);
    }

    return options;
}

function inArray(options, value)
{
    found = false;
    for(j=0; j<options.length; j++)
    {
        if(options[j] == value)
            found = true;
    }

    return found;
}

function checkLocatorCodes()
{
    // any locator codes selected?
    locs = jsGetElementById("locator");
    selected = 0;

    for(i=0; i<locs.length; i++)
    {
        if(locs[i].selected)
            selected++;
    }

    if(selected == 0)
    {
        for(i=0; i<locs.length; i++)
            locs[i].selected = true;
    }
}

function selectOption(name, value)
{
    jsGetElementById(name).value = value;
}

function clearGroup(index)
{
    selectOption("group[" + index + "]", 0);
    swapGroup(index, 0, false);
}

function addKeywordToList(keyword, listId)
{
    listObj = jsGetElementById(listId);
    if (listObj.value != '')
        listObj.value += ',';
    listObj.value += keyword;
}

function updateToggleControl(controlObj, displayId)
{
    name = controlObj.name;
    valueObj = jsGetElementById(name + "_hidden");
    value = valueObj.value;

    if (value == 0)
    {
        controlObj.src = controlObj.getAttribute("srcTrue");
        controlObj.value = 1;
        valueObj.value = 1;
        if (displayId)
            jsShowObjectById(displayId);
    }
    else
    {
        controlObj.src = controlObj.getAttribute("srcFalse");
        controlObj.value = 0;
        valueObj.value = 0;
        if (displayId)
            jsHideObjectById(displayId);
    }
}

//---------------------------------------------------------------------------
// slotEditor functions

function jsDecOrder(id, className)
{
    // className is unused for now -- it's intended use is to reorder other
    // content items to accomodate the change in this item.

    obj = jsGetElementById(id);
    order = Number(obj.value);
    order = (order > 1) ? --order : 1;
    obj.value = order;
}

function jsIncOrder(id, className)
{
    // className is unused for now -- it's intended use is to reorder other
    // content items to accomodate the change in this item.

    obj = jsGetElementById(id);
    obj.value = Number(obj.value) + 1;
}

//---------------------------------------------------------------------------
// The following functions implement an alertnative to the 'title'
// attribute tooltip. The advantage of this method, is that the tooltip
// can contain HTML.
// To use these functions, add 'tooltip' attributes to elements for which
// you'd like popup tooltips, and then add the following code somewhere
// in your HTML (preferably at the end):
//
//    <div id="tooltip" class="cma_tooltip"></div>
//    <script type="text/javascript">
//        registerTooltips();
//    </script>
//

var tooltipToId;
var tooltipBody;

function showTooltip(x, y)
{
    tipdiv = jsGetElementById("tooltip");

    tipdiv.innerHTML = '';
    tipdiv.innerHTML = tooltipBody;

    jsSetProperty("style.left", x + "px", tipdiv);
    jsSetProperty("style.top", y + "px", tipdiv);

    jsShowObject(tipdiv);
}

function startTooltip(e)
{
    if (!e)
        e = window.event

    target = (e.target) ? e.target : e.srcElement

    if (target != this)
        return;

    if (tooltipToId !== undefined)
        clearTimeout(tooltipToId);

    tooltipBody = this.getAttribute("tooltip");

    if (e.layerX)
        x = e.pageX;
    else
        x = e.clientX + document.body.scrollLeft;

    if (e.layerY)
        y = e.pageY + 25;
    else
        y = e.clientY + document.body.scrollTop + 25;

    tooltipToId = setTimeout("showTooltip(" + x + "," + y + ")", 500);
}

function endTooltip(e)
{
    if (!e)
        e = window.event

    target = (e.target) ? e.target : e.srcElement

    if (target != this)
        return;

    if (tooltipToId !== undefined)
        clearTimeout(tooltipToId);

    jsHideObject(jsGetElementById("tooltip"));
}

function registerTooltips()
{
    all = jsGetElements();

    for (var i = 0; i < all.length; i++)
    {
        tt = jsGetAttribute(all[i], "tooltip");
        if (tt != null && tt != "")
        {
            all[i].onmouseover = startTooltip;
            all[i].onmousemove = startTooltip;
            all[i].onmouseout = endTooltip;

            all[i].title = "";
        }
    }
}

function jsPopupWindow(url, hWind, nHeight, nWidth, nScroll, nResize)
{
    var cToolBar = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=" + nScroll + ",resizable=" + nResize + ",width=" + nWidth + ",height=" + nHeight;
    var popupwin = window.open(url, hWind, cToolBar);
}

function toggleFold(name)
{
	// toggle the open/close img
	imgObj = jsGetElementById(name + "-img");
	oldImg = (imgObj.src.indexOf("open") == -1) ? "closed" : "open";
	newImg = (oldImg == "open") ? "closed" : "open";
	jsSetProperty("src", imgObj.src.replace(((oldImg == "open") ? /open/ : /closed/), newImg), imgObj);
	
	// toggle the body
	jsToggleObjectById(name + "-body");
}function cavity_search(){
	if (document.search.rWhich[0].checked == true){
		document.search.action = "http://todaytonight.com.au/search/results.html";
//		document.search.target = "searchwindow";
		document.search.submit();
	}
	else if (document.search.rWhich[1].checked == true){
		document.search.action = "http://aol.com.au/aolsearch/ext.php";
//		document.search.target = "searchwindow";
		document.search.query.value = document.search.q.value;
		document.search.submit();
	}
	else {
		return false;
	}
}

function cavity_emptor(){
	document.search.action = "http://aol.com.au/aolsearch/ext.php";
//	document.search.target = "searchwindow";
	document.search.query.value = document.search.q.value;
	document.search.submit();
}

function launch_pad(URL,name,width,height,parameters) {
	var features = "width=" + width + ",height=" + height + "," + parameters;
	window.open(URL,name,features);
}

function cross_thestreams(stream){
	if (stream == "dial"){
		document.location.href = "http://seven.com.au/news/hm_040225_master";
	}
	else {
		document.location.href = "http://seven.com.au/news/hm_040225_masterbroad";
	}
}