window._scrolling_next = false;
window._scrolling_prev = false;
$(document).ready(function () {
    $("a").each(function (idx, obj) {
        if ($(obj).attr('href')) {
            if ($(obj).attr('href').indexOf('my.virginmoney.com.au') >= 0) {
                $(obj).click(function () {
                    setCookie('JSESSIONID', '', { 'expires': -5, path: "/", domain: "." + document.domain });
                    setCookie('JSESSIONID', '', { 'expires': -5, path: "/", domain: document.domain });
                });
            }
        }

    });
    $("#login").hover(
		function () {
		    $("#login-options").css('display', 'block');
		},
		function () {
		    $("#login-options").css('display', 'none');
		}
	);
    $('.pane-tabber').each(function (a, b) {
        $(b).removeClass('pane-tabber').addClass('pane-tabber-active');
        foundTab = false;
        if (document.location.hash != "") {
            $(b).find('.tabs > div').each(function (idx, tab) {
                if (document.location.hash.substring(1) == $(tab).attr('rel')) {
                    $(b).find('.tabs > div').eq(idx).addClass('current');
                    $(b).find('.panes > div').hide().eq(idx).show();
                    foundTab = true;
                }
            });
        }
        if (!foundTab) {
            $(b).find('.tabs > div:first').addClass('current');
            $(b).find('.panes > div').hide().eq(0).show();
        }
        $(b).find('.tabs > div').click(function (obj) {
            noLink = true;
            if ($(obj.target).find('a').length > 0) {
                loc = $(obj.target).find('a:first').attr('href');
                tar = $(obj.target).find('a:first').attr('target');
                if (loc != "" && loc != null) {
                    if (tar != "" && tar != null) {
                        window.open(loc, "_blank");
                    } else {
                        document.location = loc;
                    }
                    noLink = false;
                }
            }
            if (noLink) {
                $(b).find('.panes > div').hide();
                $(b).find('.panes > div').eq($(b).find('.tabs > div').index(this)).show();
                $(b).find('.tabs > div').removeClass('current').eq($(b).find('.tabs > div').index(this)).addClass('current');
            }
        });
    });


    //carousel
    if ($("#carousel").length > 0) {
        var carouselLength = $("#carousel ul li").length;
        _firstItem = $("#carousel ul li:first");
        _secondItem = $("#carousel ul li:nth-child(2)");
        _lastItem = $("#carousel ul li:last");
        $(_lastItem).clone().prependTo("#carousel ul");
        $(_firstItem).clone().appendTo("#carousel ul");
        $(_secondItem).clone().appendTo("#carousel ul");
        $("#carousel ul li:last").css("margin-right", "0");
        $("#carousel").jcarousel({
            scroll: 1,
            initCallback: mycarousel_initCallback,
            itemFirstInCallback: { onBeforeAnimation: mycarousel_onBeforeAnimation, onAfterAnimation: mycarousel_itemFirstInCallback },
            buttonNextHTML: null,
            buttonPrevHTML: null
        });
    }

    // Credit Card widget

    $(".credit-card").each(function (idx, obj) {
        var buttoncount = 0;
        var showing = 0;
        $(obj).find("ul li a").each(function (lidx, lobj) {
            if ($(lobj).parent().hasClass('active')) {
                showing = lidx;
            }
            $(lobj).click(function (btn) {
                if ($(obj).attr('rel')) {
                    $($(obj).attr('rel')).attr('href', $(lobj).attr('href'));
                } else {
                    $(obj).find("a.target-button").attr('href', $(lobj).attr('href'));
                }
                return false;
            })
        })
        $(obj).find("ul li img").each(function (lidx, lobj) {
            buttoncount++;
            $(lobj).click(function (btn) {
                $(obj).find("ul li.active").removeClass('active');
                $(lobj).parent().parent().addClass('active');
                col = lobj.src.substring((lobj.src.lastIndexOf('-') + 1), lobj.src.lastIndexOf('.'));
                $(obj).find("span:first").attr('class', col).attr('showing', lidx);
            })
        })
        $(obj).find(".trigger").each(function (tidx, tobj) {

            $(tobj).parent().attr('showing', showing);
            $(tobj).parent().attr('buttoncount', buttoncount);
            $(tobj).click(function (trigger) {
                if ((parseInt($(tobj).parent().attr('showing')) + 2) > parseInt($(tobj).parent().attr('buttoncount'))) {
                    lobj = $(tobj).parent().parent().find("span > ul li:first > a > img");
                } else {
                    lobj = $(tobj).parent().parent().find("span > ul li:nth-child(" + (parseInt($(tobj).parent().attr('showing')) + 2) + ") > a > img");
                }
                if ($(obj).attr('rel')) {
                    $($(obj).attr('rel')).attr('href', $(lobj).parent().attr('href'));
                } else {
                    $(obj).find("a.target-button").attr('href', $(lobj).parent().attr('href'));
                }
                $(obj).find("ul li.active").removeClass('active');
                $(lobj).parent().parent().addClass('active');
                imgSrc = $(lobj).attr('src');
                col = imgSrc.substring((imgSrc.lastIndexOf('-') + 1), imgSrc.lastIndexOf('.'));
                lidx = parseInt($(obj).find("span:first").attr('class', col).attr('showing')) + 1;
                if (lidx >= $(obj).find("ul li img").length) {
                    lidx = 0;
                }
                $(obj).find("span:first").attr('class', col).attr('showing', lidx);
            });
        });
    });

    // credit card compare
    var timerOBJ = "timerOBJ";
    $(".cccompare").each(function (ccidx, ccobj) {
        var id = "cccompare" + ccidx;
        if (!$(ccobj).attr('id')) {
            $(ccobj).attr('id', "cccompare" + ccidx);
        } else {
            id = $(ccobj).attr('id');
        }
        $(ccobj).attr('displayCard', 1);
        if ($(ccobj).find(" > .cards > .card").length == $(ccobj).find(" > .information > .card").length) {
            $(ccobj).find(" > .cards > .card:nth-child(2)").addClass('focus');
            $(ccobj).find(" > .information > .card:nth-child(2)").addClass('show');
            $(ccobj).find(" > .cards > .card").each(function (idx, obj) {
                $(obj).click(function () {

                    $(ccobj).find(" > .cards > .focus").removeClass('focus');
                    $(ccobj).find(" > .information > .show").removeClass('show');
                    $(this).addClass('focus');
                    $(ccobj).find(" > .information > .card:nth-child(" + (idx + 1) + ")").addClass('show');
                    $(ccobj).attr('displayCard', idx);
                    clearTimeout(window[$(ccobj).attr('id')]);
                    window[$(ccobj).attr('id')] = setTimeout("ccccompareScroll('" + $(ccobj).attr('id') + "')", 300000);
                });
            });
            window[id] = setTimeout("ccccompareScroll('" + id + "')", 150000000);
        } else {
            //fail quietly - How embarassment
        }
    });

    // Search watermark
    $("#keywords").focus(function () {
        $("#keywords").css('color', '#000000');
        if ($(this).val() == "Search...") {
            $(this).val("");
        }
    });
   
    // Highlight search result
    var searchQuery = $.getUrlVar('q');
    var searchType= $.getUrlVar('st');

    if (searchQuery != null) {
	if (window.location.href.indexOf("/search") == -1) {
    		$('#search-message-container').show();    	
	    	$('#search-term').text(unescape(searchQuery));
	    	
	    	if (searchQuery.indexOf('%20') != -1) {
	    		searchQuery = unescape(searchQuery)
		    	$("#copy:not('.side')").highlight(unescape(searchQuery)); 
	    	} else {
	    		$("#copy:not('.side')").highlight(searchQuery); 
	    	}
	    	
		// Hide tabs
		$("#copy:not('.side') .tabs, .inner-copy-container .tabs").hide();
	
		if (searchType == 'faq') {
	    		$("#copy:not('.side') .anq:contains('" + searchQuery + "')").addClass('anq-open').children('.anq-body').css('display', 'block');
	    		
	    		// Show other tab content
	    		$("#copy:not('.side') .panes").children().each(function (index) {
	    			if (index >= 1) {
		    			$(this).show();
	    			}
	    		});	
		} else {
			// Show other tab content
			$("#copy:not('.side') .panes div:hidden").show();	
		}
		// Scroll to element	
		$('html, body').animate({scrollTop: $('.highlight:first').offset().top - 100});
	}
    };
    
    $(".search-message-action a").click(function() {	
    	$('#search-message-container').slideUp("normal");
    	// Return tabs to normal
	$("#copy:not('.side') .tabs").show();

    	if (searchType == 'faq') {
    		$("#copy:not('.side') .anq").removeClass('anq-open').children('.anq-body').css('display', 'none');    
		$("#copy:not('.side') .panes").children("div:gt(0)").hide();
	} else {
		$.each($('.panes').children(), function(index, value) {
			if (index > 0) {
				$(this).hide();		
			}
		});		
	}
	
  	$('#copy').removeHighlight();	
    	return false;
    });
    
    //faq expanders

    if ($(".anq").length > 0) {
        //$("span.anq:last").addClass("anq-last");
        $(".anq .anq-head").hover(function () { $(this).addClass('anq-hover') }, function () { $(this).removeClass('anq-hover') });
        $(".anq .anq-head").bind('click', function (anq) {
            if (!$(this).parent().hasClass("anq-open")) {
                if ($(".anq-open .anq-body").length > 0) {
                	if (searchType != 'faq') {
                		$(".anq-open .anq-body").slideUp().parent().removeClass("anq-open");
                	} 
                }
                $(this).parent().addClass("anq-open");
                $(this).parent().find(".anq-body").hide().slideDown();
            } else {
        	$(this).parent().find(".anq-body").slideUp();
        	$(this).parent().removeClass("anq-open");
            }
            return false;
        })
    }
    $(".blind-trigger").each(function(idx, obj){
    	$(obj).click(function(){
    		$("#" + $(this).attr('rel')).hide().removeClass('blind').slideDown(1500);
		scrollToPos($(document).scrollTop(), $("#" + $(this).attr('rel')).position().top);

    		$(this).hide();
    		return false;
    	});
    });
    
    
    if($.getUrlVar('cid')){
	setCookie('vm_cid', $.getUrlVar('cid'), {'expires':14 * 60 * 60 * 24, path: "/", domain: document.domain, secure: false});
    }
    if($.getUrlVar('source')){
	setCookie('vm_source', $.getUrlVar('source'), {'expires':14 * 60 * 60 * 24, path: "/", domain: document.domain, secure: false});
    }
    $('a.superEmployerJoinLink, a.superIndividualsJoinLink').each(function(superIdx, superObj){
    	linkHref = $(superObj).attr('href');
    	
    	if(!(linkHref.indexOf('?cid=') > -1 || linkHref.indexOf('&cid=') > -1 || linkHref.indexOf('?source=') > -1 || linkHref.indexOf('&source=') > -1)){
	    	newURLBase = ($(superObj).hasClass('superIndividualsJoinLink')) ? '/individual_super_agree.app?' : '/employer_super_agree.app?'
	    	newURL = '';
	    	newURL += (getCookie('vm_cid')) ? 'cid=' + getCookie('vm_cid') + '&' : '';
	    	newURL += (getCookie('vm_source')) ? 'source=' + getCookie('vm_source') : '';
	    	if(newURL != ''){
		    	$(superObj).attr('href', newURLBase + newURL);
	    	}
    	}
    });
        
});

function scrollToPos(from_x, to_x){
	from_x += 25;
	window.scrollTo(0, from_x);
	if(from_x < to_x){
		setTimeout("scrollToPos(" + from_x + ", " + to_x + ")", 50);
	}
}

// Make contains function case insensitive
jQuery.expr[':'].contains = function(a,i,m){
    return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};

function setCookie(name, value, options) {
    //alert(document.cookie);
    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 * 1000));
        } else {
            date = options.expires;
        }
        expires = '; expires=' + date.toUTCString();
    }
    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('');
}
function getCookie(name){
	cookies = document.cookie.split(";");
	for(i = 0; i < cookies.length; i++){
		cookie = String(cookies[i]).split("=");
		if(String(cookie[0]).replace(/\s/, "").toLowerCase() == name){
			return (cookie.length == 2) ? cookie[1] : '';
		}
	}
}

function mycarousel_initCallback(carousel) {

    $('#carousel #next').bind('click', function () {
        carousel.next();
        return false;
    });

    $('#carousel #previous').bind('click', function () {
        if (carousel.first == 1) {
            carouselMoveToEnd(carousel);
        }
        carousel.prev();
        return false;
    });
};
function mycarousel_onBeforeAnimation(carousel, item, idx, state) {
    $(".jcarousel-list li.active").removeClass('active');
}
function mycarousel_itemFirstInCallback(carousel, item, idx, state) {
    _backwards = carousel.first < carousel.prevFirst;
    if (_backwards && idx == 1) {
        //	moved functionality on onclick event
    } else if (carousel.last == carousel.size()) {
        carousel.first = 1;
        carousel.last = 3;
        carousel.prevFirst = null;
        carousel.prevLast = null;
        carousel.animating = false;
        carousel.timer = null;
        carousel.tail = null;
        carousel.inTail = false;
        carousel.list.css('left', 0);
        idx = 1;
    }
    $("#carousel-feature div.feature").hide();
    $("#carousel-feature div.feature:nth-child(" + idx + ")").show();
    $(".jcarousel-item-" + (idx + 1)).addClass('active');
}
function mycarousel_itemLastInCallback(carousel, item, idx, state) {
    if (idx == carousel.size()) {
        carousel.reset();
    }
};
function alertObj(obj, hideValues) {
    txt = "";
    for (p in obj) {
        txt += p + ((hideValues) ? "" : " = " + obj[p]) + "\n";
    }
    alert(txt);
}
function carouselMoveToEnd(carousel) {
    moveto = 0
    for (i = 1; i < (carousel.size() - 2); i++) {
        currItem = carousel.get(i);
        moveto -= carousel.dimension(currItem);
    }
    carousel.first = carousel.size() - 2;
    carousel.last = carousel.size();
    carousel.prevFirst = carousel.size() - 3;
    carousel.prevLast = carousel.size() - 1;
    carousel.animating = false;
    carousel.timer = null;
    carousel.tail = carousel.size();
    carousel.inTail = false;
    carousel.list.css('left', moveto + "px");
}
function _next(carousel) {
    if (window._scrolling_next) {
        carousel.next();
        setTimeout(function () {
            _next(carousel);
        }, 2200);
    }
}
function _prev(carousel) {
    if (window._scrolling_prev) {
        if (carousel.first == 1) {
            carouselMoveToEnd(carousel);
        }
        carousel.prev();
        setTimeout(function () {
            _prev(carousel);
        }, 2200);
    }
}
function tncprint(obj, href) {
    window[obj].document.location = href + "?printMode=1&dt=" + new Date();
}

// Gets url paramaters
$.extend({
    getUrlVars: function () {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function (name) {
        return $.getUrlVars()[name];
    }
});

function jumpToAnchor(anchor) {
   window.location = String(window.location).replace(/\#.*$/, "") + "#" + anchor;
}

