/*
  Running MySource Matrix
  Developed by Squiz - http://www.squiz.net
  MySource, MySource Matrix and Squiz.net are registered Trademarks of Squiz Pty Ltd
  Page generated: 04 March 2009 10:02:23
*/


/*
* Global function for www.immi.gov.au written by Geoff Bailey and Ralph Flores
* This file handles specific functions for the homepage features box, top navigation bar,
* left navigation accordion, form email address redirection
* It also has generic functions for popups, bookmarking, selectbox jump menus, event loading, and leaving this site alert messages
*/


// Code for log analysis image
var log_analysis_screen_image = new Image();
log_analysis_screen_image.src = "/_img/log_analysis_info/screen_" + screen.width + "x" + screen.height + "_depth_" + screen.colorDepth + ".gif";

// START Settings for features
var feature_images = [
["/_img/homepage-features/features_annual_report.jpg","2008-2009 Annual Report"],
["/_img/homepage-features/features_resource_book.jpg","Australian Citizenship : Our Common Bond"],
["/_img/homepage-features/features_457.jpg","What's New for Employer-Sponsored Workers"],
["/_img/homepage-features/features_eaward_winner.jpg","DIAC Winner of the eAwards for Excellence in eGovernment"],
["/_img/homepage-features/features_youtube.jpg","ImmiTV on youtube"]
//["/_img/homepage-features/features_budget.jpg","Australian Government, 2009-10 Commonwealth Budget"],
//["/_img/homepage-features/features_vic_bushfires.jpg","Victorian Bushfires in February 2009"],
//["/_img/homepage-features/features_expo.jpg","Australia needs skills expos"],
//["/_img/homepage-features/features_cit_60.jpg","Celebrating 60 years of Australian Citizenship 1949-2009"]
//["/_img/homepage-features/features_newsroom.jpg","Newsroom"],
//["/_img/homepage-features/features_amep.jpg","Learn English with the AMEP"]
];
var feature_paths = [
"/about/reports/annual/2008-09/",
"http://www.citizenship.gov.au/learn/cit_test/preparing2",
"/skilled/whats_new_457.htm",
"/about/department/awards/e-award_2009.htm",
"/media/immiTV.htm"
//"/about/reports/budget/budget09/",
//"/about/special-assistance/vic-bushfire.htm",
//"/skillexpos/overseas.htm",
//"http://www.citizenship.gov.au/news/announcements/60th-anniversary.htm"
//"http://www.newsroom.immi.gov.au/",
//"/living-in-australia/help-with-english/amep/"
];
var feature_interval = 10; //in seconds
var transition_time = 0.7; //in seconds

//Setting for dthmlXCombo
window.dhx_globalImgPath="/_img/";

// functions to handle jump menu in right hand column boxes
function go_to_url(url) {
window.location = url;
}
function jumpPage(id) {
window.location = document.getElementById(id).value;
}
function jumpPage2(dhtmlX_cb) {
window.location = dhtmlX_cb.getSelectedValue();
}


// Function that allows multiple on load events
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}
function addResizeEvent(func) {
    var oldonload = window.onresize;
    if (typeof window.onresize != 'function') {
        window.onresize= func;
    }
    else {
        window.onresize= function() {
            oldonload();
            func();
        }
    }
}
//Window onload manager, carried over from previous site
//todo, identify where this script is used and convert to addLoadEvent()
function womOn(){
    window.onload = womGo;
}

function womGo(){
    for(var i = 0;i < woms.length;i++)
        eval(woms[i]);
}

function womAdd(func){
    woms[woms.length] = func;
}

var woms = new Array();

// Functions for the top menu
addLoadEvent(sfHover);
function sfHover() {
    if ($("nav")) {
        var sfEls = $("nav").childElements();
        for (var i=0; i<sfEls.length; i++) {
            sfEls[i].onmouseover=function() {
                if (this.className == "current") {
                    this.className="current_sfhover";
                }
                else if (this.className == "last") {
                    return;
                }
                else {
                    this.className=" sfhover";
                }
            }
            sfEls[i].onmouseout=function() {
                if (this.className == "current_sfhover") {
                    this.className="current";
                }
                else if (this.className == "last") {
                    return;
                }
                else {
                    this.className="";
                }
            }
        }
    }
}
addLoadEvent(highlight_top_nav);
function highlight_top_nav() {
    if ($("nav")) {
     var ul = $("nav").childElements();
     ul.each(function(j) {
     var sfEls = $A(j.getElementsByTagName("li"));
     for (var i=0; i<sfEls.length; i++) {
        sfEls[i].onmouseover=function() {
          this.className = "hover";
        }
        sfEls[i].onmouseout=function() {
          this.className = "";
        }
    }
  });
  }
}
//Give keyboard access to the drop down menus
//todo, find out why this doesnt work properly in IE, seems like there is an addition node or something
//that causes the menu to dissapear when the first nested UL is highlighted
addLoadEvent(top_nav_keyboard_axs);
function top_nav_keyboard_axs() {
    var a = $$("#top_nav a");
    a.each(function(i){
      i.onfocus = function() {
        show_sub_nav(this);
        return false;
      }
      i.onblur = function() {
        hide_sub_nav(this);
        return false;
      }
    });
}
function show_sub_nav(e) {
    var element = $(e);
      while(element.up().getAttribute("id") != "nav") {
        element = element.up();
      }
      element.addClassName("sfhover");
}
function hide_sub_nav(e) {
      var element = $(e);
      while(element.up().getAttribute("id") != "nav") {
        element = element.up();
      }
      element.removeClassName("sfhover");
}

//Script for the accordion left nav menu class
//todo, fix the menu so that no initial mennu item needs to be highlighted. Currently it works
//but the menu is glitchy when you click on the highlighted item twice
if (typeof Effect == 'undefined') throw("You must have the script.aculo.us library to use this accordion");
var defaultExpanded;
var Accordion = Class.create({
    initialize: function(id, defaultExpandedCount) {
        defaultExpanded = defaultExpandedCount;
        if(!$(id)) throw("Attempted to initalize accordion with id: "+ id + " which was not found.");
            this.accordion = $(id);
            this.options = {
                toggleClass: "accordion-toggle",
                toggleActive: "accordion-toggle-active",
                contentClass: "accordion-content"
            }
        this.contents = this.accordion.select('div.'+this.options.contentClass);
        this.isAnimating = false;
        this.maxHeight = 0;
        this.current = defaultExpandedCount ? this.contents[defaultExpandedCount-1] : this.contents[0];
        this.toExpand = null;
        this.checkMaxHeight();
        this.initialHide();
        //this.attachInitialMaxHeight();
        var clickHandler =  this.clickHandler.bindAsEventListener(this);
        this.accordion.observe('click', clickHandler);
    },

    expand: function(el) {
        this.toExpand = el.next('div.'+this.options.contentClass);
        if (this.current != 0){
            if(this.current != this.toExpand){
                this.toExpand.show();
                this.animate();
            }
            else if (defaultExpanded === 0) {
                this.toExpand.show();
                this.animate();
            }
        }
    },

    checkMaxHeight: function() {
        for(var i=0; i<this.contents.length; i++) {
            if(this.contents[i].getHeight() > this.maxHeight) {
                this.maxHeight = this.contents[i].getHeight();
            }
        }
    },

    attachInitialMaxHeight: function() {
        this.current.previous('div.'+this.options.toggleClass).addClassName(this.options.toggleActive);
        if(this.current.getHeight() != this.maxHeight) this.current.setStyle({height: this.maxHeight+"px"});
    },

    clickHandler: function(e) {
        var el = e.element();
        if(el.hasClassName(this.options.toggleClass) && !this.isAnimating) {
            this.expand(el);
        }
    },

    initialHide: function(){
        for(var i=0; i<this.contents.length; i++){
            if(this.contents[i] != this.current || defaultExpanded === 0) {
                this.contents[i].hide();
                this.contents[i].setStyle({height: 0});
            }
        }
    },

    animate: function() {
        var effects = new Array();
        var ul = this.toExpand.getElementsByTagName("ul");
        var h = ul[0].getHeight();
        var options = {
            sync: true,
            scaleFrom: 0,
            scaleContent: false,
            transition: Effect.Transitions.sinoidal,
            scaleMode: {
                originalHeight: h,
                originalWidth: this.accordion.getWidth()
            },
            scaleX: false,
            scaleY: true
        };
        effects.push(new Effect.Scale(this.toExpand, 100, options));
        options = {
            sync: true,
            scaleContent: false,
            transition: Effect.Transitions.sinoidal,
            scaleX: false,
            scaleY: true
        };
        effects.push(new Effect.Scale(this.current, 0, options));
        var myDuration = 0.4;
        new Effect.Parallel(effects, {
            duration: myDuration,
            fps: 35,
            queue: {
                position: 'end',
                scope: 'accordion'
            },
            beforeStart: function() {
                this.isAnimating = true;
                this.current.previous('div.'+this.options.toggleClass).removeClassName(this.options.toggleActive);
                this.toExpand.previous('div.'+this.options.toggleClass).addClassName(this.options.toggleActive);
            }.bind(this),
            afterFinish: function() {
                //this.current.hide();
                this.toExpand.setStyle({ height: "" });
                this.current = this.toExpand;
                this.isAnimating = false;
            }.bind(this)
        });
    }
});

addLoadEvent(loadAccordion)
function loadAccordion() {
    var ul = $$("#left_nav ul");
    var listItem = 0;
    //ie needs <ul>s set to block otherwide the menu gets glitchy
    ul.each(function(i){
        i.style.display = "block";
    });
    try {
        //getthe body class and use this to setup the default open state of the accordion
        var b = document.getElementsByTagName("body").item(0).className;
        if (b.match(/\bsub-([0-9]+)($|\s)/)[1]) {
            listItem = b.match(/\bsub-([0-9]+)($|\s)/)[1];
        }
        else {
            listItem = 0;
        }
        //if the default open position is greater than 0, we need to check for any list
        //items that have a class of "no_subs", and minus them from the default open state
        //otherwise the menu will highligh incorrectly
        if (listItem > 0) {
            var list = $("left_nav").getElementsByTagName("ul").item(0);
            var li = list.childElements();
            var no_subs = 0;
            for (var i = listItem - 1; i >= 0; i--){
                var li_children = li[i].childElements();
                li_children.each(function(j){
                    if (j.className.toLowerCase() == "no_sub") {
                        no_subs++;
                        if (i == listItem-1) {
                            listItem = 0;
                        }
                    }
                });
            }
        }
        if (listItem == 0) {
            var accordion = new Accordion("left_nav",0);
        }
        else {
            listItem = listItem - no_subs;
            var accordion = new Accordion("left_nav",listItem);
        }

    }
    catch (e) {
        try {
        var accordion = new Accordion("left_nav",0);
        }
        catch (e){
        }
    }
}

// Function that allows users to bookmark a page
function create_bookmark() {
  title = document.title;
  url = window.location;
  if (window.sidebar) { // Mozilla Firefox Bookmark
    window.sidebar.addPanel(title, url,"");
  }
  else if( window.external ) { // IE Favorite
    window.external.AddFavorite( url, title); }
  else if(window.opera && window.print) { // Opera Hotlist
    return true;
  }
}

/* ================================================================
This copyright notice must be untouched at all times.

The original version of this scriptt and the associated (x)html
is available at http://www.stunicholls.com/menu/hover_drop_1.html
Copyright (c) 2005-2007 Stu Nicholls. All rights reserved.
This script and the associated (x)html may be modified in any
way to fit your requirements.
=================================================================== */

addLoadEvent(refreshIFrames);
addResizeEvent(refreshIFrames);
function refreshIFrames() {
   if (document.getElementById('top_nav')) {
   var getEls = document.getElementById('top_nav').getElementsByTagName("IFRAME");
   for (var i=0; i<getEls.length; i++) {
    getEls.item(i).style.width = getEls.item(i).nextSibling.offsetWidth;
    getEls.item(i).style.height = getEls.item(i).nextSibling.offsetHeight;
   }
}
}

//Change features as object (function) based

addLoadEvent(loadfeatures); //comment this line out to disable the rotating advert box on the homepage!
function loadfeatures() {
    if ($("feature_container")) {
        try {
            features.init();
        }
        catch (e) {
            alert("Feature items are not loading. Please contact us for more information.");
       }
    }
}

var features = function() {

    var feature_rotation_index = 0;
    var f_interval;

    var init = function() {
        create_controls();
        randomimageid();
        f_interval = setInterval("nextimage()", feature_interval * 1000);
    };

    var randomimageid = function() {
        var l = feature_images.length;
        var rnd_no = Math.floor(l*Math.random());
        change_image(rnd_no,true);
    };

    var change_image = function(rotation_index,initial) {
        //if initial loading, don't fade hte previous screen
        if (initial) {
            this.feature_transition(rotation_index);
        }
        else {
            Effect.Appear('feature_image', { duration: transition_time, from: 1.0, to: 0.0, queue:'front' });
            setTimeout("this.feature_transition(" + rotation_index + ")",transition_time * 1000);
        }
        Effect.Appear('feature_image', { duration: transition_time, from: 0.0, to: 1.0, queue:'end' });
        //reset Interval
        setTimeout("this.reset_interval()", transition_time * 1000);
    };

    this.feature_transition = function(rotation_index) {
        update_indicators(rotation_index);
        feature_rotation_index = rotation_index;
        $("feature_image").src = feature_images[rotation_index][0];
        //change the alt text
        $("feature_image").alt = feature_images[rotation_index][1];
        $("feature_image").title = $("feature_image").alt;
        //change the url
        $("feature_path").setAttribute("href",feature_paths[rotation_index]);
    };

    var previmage = function() {
        if (feature_rotation_index > 0)
            feature_rotation_index--;
        else
              feature_rotation_index = feature_images.length - 1;

        //change to previous image
        change_image(feature_rotation_index);
    };

    this.nextimage = function() {
     if(feature_rotation_index < feature_images.length - 1)
            feature_rotation_index++;
        else
              feature_rotation_index = 0;

        //change to previous image
        change_image(feature_rotation_index);
    };

  var create_controls = function() {
        create_prevnext();
        create_indicators();
    };

    var create_prevnext = function() {
        //previous button
        var newdiv = document.createElement('div');
        newdiv.setAttribute("id","feature_prev");
        newdiv.onclick = function() { previmage(); return false; };


        $("feature_bottom").appendChild(newdiv);
        //next button
        var newdiv = document.createElement('div');
        newdiv.setAttribute("id","feature_next");
        newdiv.onclick = function() { nextimage(); return false; };
        $("feature_bottom").appendChild(newdiv);
    };


    var create_indicators = function() {


        var newdiv = document.createElement('div');
        newdiv.setAttribute("id","feature_indicators_box");
        newdiv.style.width = (feature_images.length * 18) + "px";
        $("feature_bottom").appendChild(newdiv);
        for (var i=0; i<feature_images.length; i++) {
            var newdiv = document.createElement('div');
            newdiv.setAttribute("id","f_indicator" + i);
            newdiv.className = "feature_inactive";
            newdiv.onclick = function() { change_image(this.id.replace("f_indicator","")); return false; };
            $("feature_indicators_box").appendChild(newdiv);
        }
    };

    var update_indicators = function(index) {
        for (var i=0; i<feature_images.length; i++) {
            if (parseInt(index) == i)
                $("f_indicator" + i).className = "feature_active";
            else
                $("f_indicator" + i).className = "feature_inactive";
        }
    };

    this.reset_interval = function() {
        clearInterval(f_interval);

        f_interval = setInterval("this.nextimage()", feature_interval * 1000);
    };


    return {
                init:init
    };

}();


//This function changes the heading of the eForm pages. Page needs to have a query string
function replaceH1(){
    var docURL = window.location.toString();
    if (docURL.indexOf("?") != -1) {
        var queryString = docURL.split("?")[1];
        var heading = document.getElementById('content').getElementsByTagName('h1')[0];
        //heading.firstChild.nodeValue=queryString;
        if(queryString==1){
            heading.firstChild.nodeValue="Trade Skills Training visa enquiries";
        }
        else if(queryString==2){
            heading.firstChild.nodeValue="Professional Development Visa Enquiries";
        }
        else if(queryString==6){
            heading.firstChild.nodeValue="Perth Offshore Students Processing Centre";
        }
        else if(queryString==7){
            heading.firstChild.nodeValue="Agent AL2-4 eVisa trial enquiry form (People\'s Republic of China or India only)";
        }
        else if(queryString==8){
            heading.firstChild.nodeValue="Agent AL2-4 eVisa trial enquiry form (Indonesia or Thailand only)";
        }
        else if(queryString==9){
            heading.firstChild.nodeValue="Employer Sponsored Workers (e457) Enquiry Form - Adelaide";
        }
        else if(queryString==10){
            heading.firstChild.nodeValue="Employer Sponsored Workers (e457) Enquiry Form - Brisbane";
        }
        else if(queryString==11){
            heading.firstChild.nodeValue="Employer Sponsored Workers (e457) Enquiry Form - Canberra";
        }
        else if(queryString==12){
            heading.firstChild.nodeValue="Employer Sponsored Workers (e457) Enquiry Form - Darwin";
        }
        else if(queryString==13){
            heading.firstChild.nodeValue="Employer Sponsored Workers (e457) Enquiry Form - Hobart";
        }
        else if(queryString==14){
            heading.firstChild.nodeValue="Employer Sponsored Workers (e457) Enquiry Form - Melbourne";
        }
        else if(queryString==15){
            heading.firstChild.nodeValue="Employer Sponsored Workers (e457) Enquiry Form - Parramatta";
        }
        else if(queryString==16){
            heading.firstChild.nodeValue="Employer Sponsored Workers (e457) Enquiry Form - Perth";
        }
        else if(queryString==18){
            heading.firstChild.nodeValue="Employer Sponsored Workers (e457) Enquiry Form - Sydney CBD";
        }
        else if(queryString==19){
            heading.firstChild.nodeValue="Resident Return Visas Enquiry Form";
        }
        else if(queryString==20){
            heading.firstChild.nodeValue="Citizenship Applications Enquiry Form";
        }
        else if(queryString==21){
            heading.firstChild.nodeValue="Canberra Business Centre";
        }
        else if(queryString==22){
            heading.firstChild.nodeValue="Sydney CBD Business Centre";
        }
        else if(queryString==23){
            heading.firstChild.nodeValue="Darwin Business Centre";
        }
        else if(queryString==24){
            heading.firstChild.nodeValue="Brisbane Business Centre";
        }
        else if(queryString==25){
            heading.firstChild.nodeValue="Adelaide Business Centre";
        }
        else if(queryString==26){
            heading.firstChild.nodeValue="Hobart Business Centre";
        }
        else if(queryString==27){
            heading.firstChild.nodeValue="Melbourne Business Centre";
        }
        else if(queryString==28){
            heading.firstChild.nodeValue="Perth Business Centre";
        }
        else if(queryString==29){
            heading.firstChild.nodeValue="Parramatta Business Centre";
        }
        else if(queryString==30){
            heading.firstChild.nodeValue="Sydney Entertainment Processing Centre";
        }
        else if(queryString==31){
            heading.firstChild.nodeValue="Adelaide Offshore Student Processing Centre (AOSPC)";
        }
        else if(queryString==32){
            heading.firstChild.nodeValue="Adelaide Offshore Student Processing Centre (AOSPC)";
        }
        else if(queryString==33){
            window.location="http://e7static.immi.gov.au/contacts/visa-enquiries/professionals.htm";
        }
        else if(queryString==35){
            heading.firstChild.nodeValue="First Working Holiday Application enquiry form";
        }
        else if(queryString==36){
            heading.firstChild.nodeValue="Second Working Holiday Application enquiry form";
        }
        else if(queryString==37){
            heading.firstChild.nodeValue="e676 Outside Australia application enquiry form";
        }
        else if(queryString==38){
            heading.firstChild.nodeValue="e676 In Australia application enquiry form";
        }
        else if(queryString==39){
            heading.firstChild.nodeValue="e676 Gulf Countries application enquiry form";
        }
        else if(queryString==40){
            heading.firstChild.nodeValue="Hobart Special Program Processing Centre";
        }
        else if(queryString==41){
            heading.firstChild.nodeValue="NSW Offshore Humanitarian Processing Centre";
        }
        else if(queryString==42){
            heading.firstChild.nodeValue="Perth Business Skills Processing Centre";
        }
        else if(queryString==43){
            heading.firstChild.nodeValue="Parent Visa Centre enquiry form";
        }
        else if(queryString==44){
            heading.firstChild.nodeValue="Victoria Offshore Humanitarian Processing Centre";
        }
        else if(queryString==50){
            heading.firstChild.nodeValue="Employer Sponsored Permanent Visas enquiry form";
        }
        else if(queryString==51){
            heading.firstChild.nodeValue="Health Operations Centre";
        }
        else if(queryString==67){
            heading.firstChild.nodeValue="Sydney CBD Centre of Excellence";
        }
        else if(queryString==68){
            heading.firstChild.nodeValue="Parramatta Centre of Excellence";
        }
        else if(queryString==69){
            heading.firstChild.nodeValue="Special Activities (temporary residence) visa enquiries";
        }
        else if(queryString==72){
            heading.firstChild.nodeValue="Adelaide Business Skills Processing Centre ";
        }
        else if(queryString==74){
            heading.firstChild.nodeValue="eHealth Enquiry and Feedback Form";
        }
		else if(queryString==78){
            heading.firstChild.nodeValue="Child and Other Family Processing Centre Enquiry Form";
        }
		else if(queryString==83){
            heading.firstChild.nodeValue="Canberra Second Stage Partner Processing Centre enquiry form";
        }
    }
}

//This function reset forms on page load
function clearForms() {
     var i;
    if (document.forms.lenght > 0) {
        for (i = 0; i < document.forms.length; i++) {
            document.forms[i].reset();
        }
    }
}

addLoadEvent(loadForms);
function loadForms(){
    replaceH1();
    clearForms();
}
function MM_jumpMenu(targ,selObj,restore) {
     eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
     if (restore) {
         selObj.selectedIndex=0;
    }
}
function MM_findObj(n, d) {
      var p,i,x;
      if (!d) {
          d=document;
      }
      if ((p=n.indexOf("?"))>0&&parent.frames.length) {
          d=parent.frames[n.substring(p+1)].document;
          n=n.substring(0,p);
      }
      if (!(x=d[n])&&d.all) {
          x=d.all[n];
          for (i=0;!x&&i<d.forms.length;i++) {
              x=d.forms[i][n];
          }
          for(i=0;!x&&d.layers&&i<d.layers.length;i++) {
              x=MM_findObj(n,d.layers[i].document);
          }
          if(!x && d.getElementById) {
              x=d.getElementById(n);
              return x;
          }
      }
}
function MM_jumpMenuGo(selName,targ,restore){
    var selObj = MM_findObj(selName);
    if (selObj) {
        MM_jumpMenu(targ,selObj,restore);
    }
}
function openWindow(url, name) {
    win = window.open(url, name,"directories=no,location=no,menubar=yes,resizable=yes,scrollbars=yes,toolbar=no,width=800,height=600,left=10,right=0,top=10,bottom=0");
    win.focus();
}
function ministerAlert(string){
	var text = "You are now leaving the Department of Immigration and Citizenship website"
	if (string) {
		text += string;	
	}
	alert(text);
}
function leavingSiteAlert(string){
	if (string.indexOf("You are now leaving") != -1) {
		var text = string;
	}
	else {
		var text = "You are now leaving the Department of Immigration and Citizenship website";
		if (string) {
			text = text + ". " + string;	
		}
	}
	
	var answer = confirm(text/* + "\r\n\r\nDo you wish to proceed?"*/);
	if (!answer){
		return false;
	}
}


function processEcomLinks() {
    $$("a").each(function(link) {
        if (link.href.indexOf("https://www.ecom.") > -1) {
             link.onclick = function(){
                 var win = window.open(this.href,'new_window','toolbar=0,location=0,scrollbars=1,directories=0,status=0,menubar=0,resizable=1');
				 win.focus();
                 return false;
             };
		}						  
    });
}

function anchorsToOpenWindow(classname, IsWithToolbar) {
    $$(classname).each(function(link) {
        link.onclick = function(){
			 if (IsWithToolbar) {
                 var win = window.open(this.href,'new_window','');
				 win.focus();
			 } else {
                 var win = window.open(this.href,'new_window','toolbar=0,location=0,scrollbars=1,directories=0,status=0,menubar=0,resizable=1');
				 win.focus();
			 }
             return false;
        };
    });
}

