/*
  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: 30 November 2009 10:20:58
*/


// START Settings for features

var feature_interval = 10; //in seconds
var transition_time = 0.7; //in seconds

// START Settings and functions for dthmlXCombo
window.dhx_globalImgPath = "/_img/";

function jumpPage2(dhtmlX_cb) {
window.location = dhtmlX_cb.getSelectedValue();
}

//This function reset forms on page load
function clearForms() {
    var i;
    if (document.forms.length > 0) {
        for (i = 0; i < document.forms.length; i++) {
            document.forms[i].reset();
        }
    }
}

// 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;
    }
}

//New window function
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();
}

//Leaving site alert
function ministerAlert(string){
    var text = "You are now leaving the Department of Immigration and Citizenship website";
    if (string) {
        text += string;
    }
    alert(text);
}

//New leaving site alert with optional parameter
function leavingSiteAlert(string){
    var text;
    if (string.indexOf("You are now leaving") != -1) {
        text = string;
    }
    else {
        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 addResizeEvent(func) {
    var oldonload = window.onresize;
    if (typeof window.onresize != 'function') {
        window.onresize= func;
    }
    else {
        window.onresize= function() {
            oldonload();
            func();
        }
    }
}

function refreshIFrames() {
    if ($('#top_nav')[0]) {
        $("#top_nav iframe").each(function(){
            var ul = $(this).next();
            $(this).width(ul.width());
            $(this).height(ul.height());
            $(this).css("top",ul.css("top"));
            $(this).css("left",ul.css("left"));
            $(this).css("margin-left","-10px");
        });
    }
}

var features = function() {
    //feature-box based variables
    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 the previous screen
        if (initial) {this.feature_transition(rotation_index);}
        else {
            //hide the old image
            $("#feature_image").fadeOut(transition_time * 1000);
            setTimeout("this.feature_transition(" + rotation_index + ")",transition_time * 1000);
        }
        //display the next image
        $("#feature_image").fadeIn(transition_time * 1000);
        //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")[0].src = feature_images[rotation_index][0];
        //change the alt text
        $("#feature_image")[0].alt = feature_images[rotation_index][1];
        $("#feature_image")[0].title = $("#feature_image")[0].alt;
        //change the url
        $("#feature_path")[0].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
        $('<div id="feature_prev"></div>').appendTo('#feature_bottom').click(function() {
            previmage();
            return false;
        });
        //next button
        $('<div id="feature_next"></div>').appendTo('#feature_bottom').click(function() {
            nextimage();
            return false;
        });
    };
    var create_indicators = function() {
        //create feature box container
        $('<div id="feature_indicators_box"></div>').width(feature_images.length * 18).appendTo('#feature_bottom');
        //add the indicator buttons
        $.each(feature_images,function(index, item) {
            $('<div id="' + ("f_indicator" + index) + '"></div>').appendTo("#feature_indicators_box").addClass("feature_inactive").click(function() {
                change_image(this.id.replace("f_indicator",""));
                return false;
            });
        });
    };
    var update_indicators = function(index) {
        for (var i=0; i<feature_images.length; i++) {
            if (parseInt(index,10) == i){$("#f_indicator" + i)[0].className = "feature_active";}
            else {$("#f_indicator" + i)[0].className = "feature_inactive";}
        }
    };
    this.reset_interval = function() {
        clearInterval(f_interval);
        f_interval = setInterval("this.nextimage()", feature_interval * 1000);
    };
    return {
        init:init
    };
}();

// Feature box
function loadFeatures() {
    if ($("#feature_container")[0] && feature_images.length > 1) {  // check if the feature box div exist
        try {features.init();}
        catch (e) {}
    }
}

//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"; }
    }
}

//nextUntil plugin for jQuery. Un-official plugin that selects all elements until a specific element is reached
jQuery.fn.nextUntil = function(expr, include) {
    var match = [];
    include = include ? true : false;
    // We need to figure out which elements to push onto the array
    this.each(function(){
        // Traverse through the sibling nodes
        for( var i = this.nextSibling; i; i = i.nextSibling ) {
            // Make sure that we're only dealing with elements
            if ( i.nodeType != 1 ) {continue;}
            // Add it on to the stack if include is set
            if ( include ) {
                match.push( i );
            }
            // If we find a match then we need to stop
            if ( jQuery.filter( expr, [i] ).length ) {break;}
            // Add it on to the stack if include is not set
            if (! include ) { match.push( i ); }
        }
    });
    return this.pushStack( match, arguments );
};

//Setup the top nav, expandable and accordion sections, and init any other functions that may be required here
$(document).ready(function(){
    //Process top navigation
    $("#nav").children().each(function(){
        //Highlight top level items
        $(this).find("ul:first").hide();
        $(this).hover(
            function () {
                $("#nav").children().each(function(){
                    $(this).find("ul:first").stop(true,true);
            });
            $(this).find("ul:first").css("left","auto").hide().slideDown("fast").attr("class","sfhover");
            $(this).find("iframe:first").slideDown("fast").css("left","auto");
            },
            function () {
                $("#nav").children().each(function(){
                $(this).find("ul:first").stop(true,true);
            });
            $(this).find("ul:first").hide().slideUp("fast").attr("class","").css("left","-999em");
            $(this).find("iframe:first").slideUp("fast").css("left","-999em");
            }
        );
        //Highlight second level items
        $(this).find("li").each(function(){
            $(this).hover(
                function () {
                    $(this).attr("class","hover");
                },
                function () {
                    $(this).attr("class","");
                }
            );
        });
    });
    if ($("#left_nav")[0]) {
        //Loop through the left nav li's and highlight the current item
		var url = jQuery.url.attr("source");
		$("#left_nav li").each(function(){
				var a = $(this).find("a:first");
				var href = $(a).attr("href");
				if (url.indexOf(href) != -1) {
					$(a).addClass("current");
					var p = $(this).parent().parent().parent();
					if ($(p)[0].tagName.toLowerCase() == "li") {
						$(p).addClass("showThis");
						$(p).addClass("selected");
					}
				}
		});

        //Init navigation accordion
        var left_nav_acc = new jqAccordion({
                animation: "slide",
                container: "#left_nav",
                item: "li.level-1",
                header: "div.accordion-toggle",
                body: "ul",
                speed: 250
            });
    }
    //Init expandable/collasible content panels
    if ($("body:first").hasClass("expandable-sections")) {
        $("#content h2").each(function(){
            $(this).css("cursor","pointer");
            $(this).addClass("collapsed");
            $(this).nextUntil("h2").wrapAll("<div class='content-block'></div>");
            if ($(this).hasClass("show")) {
                $(this).next().show();
                $(this).toggleClass("collapsed");
                $(this).toggleClass("expanded");
            }
            else {
                $(this).next().hide();
            }
            $(this).click(function(){
                if ($(this).hasClass("collapsed")) {
                    $(this).next().fadeIn("fast");
                }
                else {
                    $(this).next().fadeOut("fast");
                }
                if ($(this).attr("class") !== "") {
                    $(this).toggleClass("collapsed");
                    $(this).toggleClass("expanded");
                }
                return false;
            });
            $(this).contents().wrap("<a href='#.'></a>");
        });
        if ($("#content h2").length > 1) {
            $("#content h2:first").before("<div class='expand_all'><a href='#' class='expand_all'>Show all</a><a href='#' class='collapse_all'>Hide all</a></div>");
            $("div.expand_all:first").find("a.expand_all").click(function(){
                $("#content h2").each(function(){
                    $(this).nextUntil("h2").show();
                    $(this).attr("class","expanded");
                });
            });
            $("div.expand_all:first").find("a.collapse_all").click(function(){
                $("#content h2").each(function(){
                    $(this).nextUntil("h2").hide();
                    $(this).attr("class","collapsed");
                });
            });
        }
    }

    //Init accordion content panels
    if ($("body:first").hasClass("accordion")) {
        if ($("#content h2").length > 1) {
            $("#content h2").each(function(i,elem){
                $(this).addClass("accordion-toggle");
                $(this).click(function(){
                    $.cookie('accordion-panel', i + ',' + jQuery.url.attr("source"));
                });
                var h = $(this).nextUntil("h2");
                var ar = $.makeArray($(this));
                ar = $.merge(ar,h);
                $(ar).wrapAll("<div class='accordion-item'></div>");
                $(this).nextUntil("h2").wrapAll("<div class='accordion-content'></div>");
                //Get currently opened panel from cookie
                if ($.cookie('accordion-panel')) {
                    var ckString = $.cookie('accordion-panel');
                    ckVal = ckString.split(",");
                    if (ckVal[0] == i && jQuery.url.attr("source") == ckVal[1]) {
                        $(this).parent().addClass("showThis");
                    }
                }
            });
        }
        //Init accordion panels
        var content_acc = new jqAccordion({
            animation: "slide",
            container: "#content",
            item: "div.accordion-item",
            header: "h2.accordion-toggle",
            body: "div.accordion-content",
            speed: 250
        });
    }
    else if ($("body:first").hasClass("multi-accordion")) {
        $("#content div.accordion").each(function(j,elem){
            $(this).find("h2").each(function(i,elem){
                $(this).addClass("accordion-toggle");
                $(this).click(function(){
                    $.cookie('multi-accordion-panel', i + ',' + jQuery.url.attr("source") + ',' + j);
                });
                var h = $(this).nextUntil("h2");
                var ar = $.makeArray($(this));
                ar = $.merge(ar,h);
                $(ar).wrapAll("<div class='accordion-item'></div>");
                $(this).nextUntil("h2").wrapAll("<div class='accordion-content'></div>");
                //Get currently opened panel from cookie
                if ($.cookie('multi-accordion-panel')) {
                    var ckString = $.cookie('multi-accordion-panel');
                    ckVal = ckString.split(",");
                    if (ckVal[0] == i && jQuery.url.attr("source") == ckVal[1] && ckVal[2] == j) {
                        $(this).parent().addClass("showThis");
                    }
                }
            });
            //Init accordion panels
            new jqAccordion({
                animation: "slide",
                container: "#content",
                item: "div.accordion-item",
                header: "h2.accordion-toggle",
                body: "div.accordion-content",
                speed: 250
            });
        });
    }
    $("h2.accordion-toggle").each(function(){
        var str = $(this).text();
        $(this).wrap("<div class='header'></div>").before("<div class='left'></div>").after("<div class='right'></div>");
        $(this).html("<a href='#'>" + str + "</a>");
    });

    //Look for a next page link and append it to the content
    if ($("body:first").hasClass("accordion") || $("body:first").hasClass("expandable-sections")) {
        var p = $("#content").find("p.next-page:first").clone();
        $(p).appendTo("#content:first").show();
        $("#content").find("p.next-page:first").remove();
        var flashContainer = $("#content").find("div.flash_container:first").clone();
        $(flashContainer).appendTo("#content:first").show();
        $("#content").find("div.flash_container:first").remove();
        if ($("div.after-expandable-sections")[0]){
            var div_clone = $("div.after-expandable-sections").clone();
            $(div_clone).appendTo("#content:first").show();
            $("#content").find("div.after-expandable-sections:first").remove();
        }
    }

    //Process popup links
    $("a.newWindow").click(function(){
        var w = window.open($(this).attr("href"),"immi_popup","height=768,width=1000,location=no,menubar=no,resizable=yes,scrollbars=no,status=no,titlebar=yes,toolbar=no");
        return false;
    });
    $.fn.colorbox.settings.opacity = "0.5";
    //$("#content a.popup").colorbox({transition:"none", width:"85%",height:"85%",iframe:true});
    if(!$("body:first").hasClass("gmap")) {
        $("#content a").each(function(){
            if ($(this).attr("href") && $(this).attr("href").indexOf("#") == -1){
                var aText = $(this).attr("href");
                var domain = jQuery.url.attr("host");
                if (aText.toLowerCase().indexOf("citizenship.gov.au") == -1 && aText.toLowerCase().indexOf("immi.gov.au") == -1 ) {
                    if (aText.toLowerCase().indexOf("http://") != -1){
                        $(this).addClass("external");
                        $(this).click(function(){
                            ministerAlert();
                        });
                    }
                }
                if (aText.toLowerCase().indexOf(".pdf") != -1) {
                    $(this).addClass("pdf");
                }
                if ($(this).hasClass("popup")) {
                    $(this).colorbox({transition:"none", width:"85%",height:"85%",iframe:true,close:"Close"});
                }
            }
        });
    }
    if ($("#content div.flash_audio")[0]) {
        $("#content div.flash_audio").each(function(){
            var id = $(this).attr("id");
            var img = $(this).find("img:first").attr("src");
            var mp3 = $(this).find("a:first").attr("href");
            var caption = "";
            if ($(this).find("p:first")[0]) {caption = $(this).find("p:first").html();}
            $(this).html("");
            $f(id, "/gateways/police/__designs/javascript_files/globals.js/flowplayer-3.1.1.swf", {
                plugins: {
                    audio: {
                        url: "/gateways/police/__designs/javascript_files/globals.js/flowplayer.audio-3.1.0.swf"
                    },
                    controls: {
                        fullscreen: false,
                        time: false,
                        volume: false,
                        mute: false
                    }
                },
                // first entry in the playlist works as splash and second entry is the audio file
                playlist: [
                    {url: img, scaling: 'original'},
                    // our MP3 does not start automatically
                    {url: mp3, autoPlay: false}

                ]
            });
            if (caption !== "") {$(this).append("<p>" + caption + "</p>");}
            $(this).corners();
        });
    }
    if ($("#content div.flash_video")[0]) {
        $("#content div.flash_video").each(function(){
        $(this).find("a:first").each(function(){
                flowplayer($(this).attr("id"), {
                    src: "/gateways/police/__designs/javascript_files/globals.js/flowplayer-3.1.1.swf",
                    wmode:"opaque"},
                {
                clip: {
                    scaling:'orig',
                    // these two configuration variables does the trick
                    autoPlay: false,
                    autoBuffering: true
                }
            });
        });
        $(this).corners();
        });
    }/*
    if ($("#content a[href*=.flv]")[0]){
        $("#content a[href*=.flv]").flowplayer("/gateways/police/__designs/javascript_files/globals.js/flowplayer-3.1.1.swf",  {
            clip: {
                scaling:'orig',
                // these two configuration variables does the trick
                autoPlay: false,
                autoBuffering: true,
            },
            wmode:'opaque'
        });

    }*/
    /*var objects = document.getElementsBytagname("object");
    for (var i = 0; i < objects.length; i++){
        objects[i].focus();
        objects[i].wmode = "opaque";
    }*/
    /*if ($("#content object")[0]){
        $("#content object").each(function(){
                var param = "<param name='wmode' value='opaque'></param>";
                $(this).html("<p>hi</p>");
                alert($(this).html());
                $(this).append(param);
        });
    }*/
    //process link types
    $("#bookmarks_link").click(function(){
        create_bookmark();
        return false;
    });
    $("#print_link").click(function(){
        window.print();
        return false;
    });
    //Load these function
    replaceH1();
    loadFeatures();
    addResizeEvent(refreshIFrames);
    refreshIFrames();
});

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
