var sliderIndex = 0;
var panels = [];
var zIndex = 0;
$(document).ready(function (){
	createSlider();
	if (window["CMSLib"] == null || window["CMSLib"] == undefined){
	    createLinkPanels();
	}
});
function createLinkPanels (){
	var panels = $('.linkpanel');
	panels.each(function (){
		var link = $(this).find("a").eq(0);
		var href = link.attr("href");
		link.attr("href", "javascript:void(0)");
		$(this).click(function(){
			location.href = href;
		}).mouseover(function (){
			$(this).css("cursor", "pointer");
			$(this).toggleClass("hover", true);
		}).mouseout(function (){
			$(this).css("cursor", "default");
			$(this).toggleClass("hover", false);
		});
	});
}
var sliding = false;
function createSlider(){
	var slider = $('#slider');
	var height = 0;
	panels = $('#slider .panel').css({
		'position' : 'absolute',
		'top' : '0px',
		'left' : '262px'
	}).each(function(){
		if (height < $(this).height()){
			height = $(this).height();
		}
	});
	slider.css("height", height+'px');
	$(panels[0]).css('left', '0px');
	$('#slider-forward').click(function (){
	   if (!sliding){
	        sliding = true;
		    $(panels[sliderIndex]).stop().animate({
			    'left' : '-262px'
		    }, 1000);
		    sliderIndex++;
		    if (sliderIndex > panels.length-1){
			    sliderIndex = 0;
		    }
		    $(panels[sliderIndex]).stop().css({"left" : "262px", "zIndex" : zIndex++}).animate({
			    'left' : '0px'
		    }, 1000, function (){
		        sliding = false;
		    });
	    }
	}).attr("href", "javascript:void(0);");
	$('#slider-back').click(function (){
	    
	   if (!sliding){
	        sliding = true;
		    $(panels[sliderIndex]).stop().animate({
			    'left' : '262px'
		    }, 1000);
		    sliderIndex--;
		    if (sliderIndex < 0){
			    sliderIndex = panels.length-1;
		    }
		    $(panels[sliderIndex]).stop().css({"left" : "-262px", "zIndex" : zIndex++}).animate({
			    'left' : '0px'
		    }, 1000, function (){
		        sliding = false;
		    });
		 }
	}).attr("href", "javascript:void(0);");
}

  var z = 1000;
$(document).ready(function (){
	$(".mainnav a").each(function (){
	
	var rel = $(this).attr("rel");
	if (rel != null && rel != ""){
	    var yoffset = 2;
	    var xoffset = 5;
	    if (rel.indexOf(":")>-1){
	        var parts = rel.split(":");
	        rel = parts[0];
	        offsets = parts[1].split(".");
	        var yoffset = offsets[0];
	        var xoffset = offsets[1];
	    }
	    $(this).attr("rel", rel);
	    $(this).attr("xoff", xoffset);
	    $(this).attr("yoff", yoffset);
	    
		if ($('#'+rel).length > 0){
			var related = $('#'+rel).eq(0);
			related.css("opacity", 0);
			related[0].timeout = null;
			related.mouseover(function (){
				clearTimeout($(this)[0].timeout);
				$(this).css("z-index", z++);
				$(this).stop(true);
				$(this).show();
				$(this).fadeTo(150, 1);
				$(".mainnav a[rel="+$(this).attr("id")+"]").toggleClass("hover", true);
			}).mouseout(function (){
				$(this).stop(true);
				var self = this;
				if ($(this).css("opacity") < 1){
					$(".mainnav a[rel="+$(this).attr("id")+"]").toggleClass("hover", false);
					$(this).fadeTo(150, 0, function (){
						$(this).hide();
					});
				}else {

					$(this)[0].timeout = setTimeout(function (){
						$(".mainnav a[rel="+$(self).attr("id")+"]").toggleClass("hover", false);
						$(self).fadeTo(10, 0, function (){
							$(this).hide();
						});
					}, 10);
				}
			});
			$(this).mouseover(function (){
				related.css("z-index", z++);
				related.stop(true);
				related.show();
				related.fadeTo(150, 1);
				related.css("left", $(this).position().left-$(this).attr("xoff"));
				related.css("top", $(this).position().top+$(this).height()-$(this).attr("yoff"));
				clearTimeout(related[0].timeout);
				$(this).toggleClass("hover", true);

			}).mouseout(function (){
				related.stop(true);
				var self = this;
				if (related.css("opacity") < 1){
					$(self).toggleClass("hover", false);
					related.fadeTo(150, 0, function (){
						related.hide();
					});
				}else {	
					related[0].timeout = setTimeout(function (){
						$(self).toggleClass("hover", false);
						related.fadeTo(10, 0, function (){
							related.hide();
						});
					}, 10);
				}
			});
		}
	}
	});
});

$(document).ready(function (){
	var inputs = $('input[type=text]');
	inputs.focus(function (){
		if (this.value == this.title){
			this.value = '';
		}
	}).blur(function (){
		if (this.value == ''){
			this.value = this.title;
		}
	});
});

$(document).ready(function() {
    $('table.sortable-table').tablesorter();
});

$(document).ready(function (){
	if (window["CMSLib"] == null || window["CMSLib"] == undefined){
        $('#your .box').mouseover(function (ev){
            this.img.stop();
            this.img.fadeTo( 200, 1);
        }).mouseout(function (ev){
            this.img.stop();
            this.img.fadeTo( 200, 0);
        }).each(function (ev){
            this.img = $(this).find("img.over");
            this.p = $(this).find("p");
            this.img.css("opacity", 0);
        });
    }else {
        $('#your .box img.over').css("display", "none");
    }
});

$(document).ready(function (){

	if (window["CMSLib"] == null || window["CMSLib"] == undefined){
    var old = null;
    $('ul.faqs h3').click(function (){
        var x = this;
        if (old != null){
            if (old[0] != $(this.parentNode).find("div")[0]){
                
                $(old.parentNode).find("h3").toggleClass("selected", false);
                old.slideUp("fast", function (){
                    $(x.parentNode).find("div").slideDown("fast");
                });
            }else {
                return;
            }
        }else {
            $(this.parentNode).find("div").slideDown("fast");
        }
        $(this).toggleClass("selected", true);
        old = $(this.parentNode).find("div");
    }).mouseover(function (){
        $(this).toggleClass("hover", true);
    }).mouseout(function (){
        $(this).toggleClass("hover", false);
    }).css("cursor","pointer");
    $('ul.faqs div').hide();
    }
});

$(document).ready(function (){
    var counter = 0;
    var position = 1;
    var index = 0;
    var current = 0;
    var currentlink = null;
    var divs = [];
    var maxfades = $('#section-header-right div.fade').size()-1;
    var fadetime = 6000;
    
    $('#section-header-right div.fade').each(function (){
        if (counter != 0){
            $(this).css("display", "none");
        }
        divs.push($(this));
        counter++;
    }).css({
        'position' : 'absolute'
    })
    $('#section-header-right').append('<div class="controls"></div>');
    
    var currentslide = 0;
	var timeout = null;
    
	function bannerslide(pos) {

		if (pos > maxfades) {pos = 0;}
		
		var link = $('a.dot[rel='+(pos)+']');
		var prevlink = $('a.dot[rel='+(currentslide)+']');

		$(link).toggleClass("selected", true);
		$(prevlink).toggleClass("selected", false);
				
		divs[currentslide].fadeOut("fast", function (){
			divs[pos].fadeIn("fast");
		});
		
		currentslide = pos;
		
		if($(divs).size()  > 1) {
			timeout = setTimeout(autobannerslider, fadetime);
		}
		
	}
	
	function autobannerslider() {
		clearTimeout(timeout);
		bannerslide(currentslide+1);
		if (currentslide > maxfades) {currentslide = 0;}
	}
	
	function bannersliderClickHandler() {
		clearTimeout(timeout);
		if (!$(this).hasClass('selected')){
			bannerslide(parseInt($(this).attr('rel')));
		}
	}
    
    $(divs).each(function (){
        var link = document.createElement("a");
        link.className = 'dot';
        link.href = 'javascript:void(0);';
        link.rel = index; 

        $(link).click(bannersliderClickHandler);

        if (index == 0){
            $(link).toggleClass("selected", true);
            currentlink = $(link);
        }
        $('#section-header-right div.controls').append(link);
        index++;
    });
    var width = (divs.length*16);
    if ($('#section-header-right').hasClass("centercontrols")){

        $('#section-header-right div.controls').css({
                "width": width+'px',
                "left": ((380/2)-(width/2))+'px'
                });
   }

	if($(divs).size() > 1) {
		var timeout = setTimeout(autobannerslider, fadetime);
	}
});

/* Code for the fund table in the fund buy process */
$(document).ready(function() {
    $('#SelectedProduct, #SelectedProvider').change(function() {
        $(this).submitAndMoveToLocation('fundselection', 'btnUpdateUnits')
    })

    $('#btnAdd').click(function() {
        $(this).submitAndMoveToLocation('fundselection', 'btnAdd')
    })

    if (window.location.hash == '#fundselection') {
        $('#funds').effect('highlight', {}, 1000);
    }

});

$(document).ready(function() {

//    $('#FundManager').change(function() {
//        $(this).submitAndMoveToLocation('fundselection')
//    })
//
//   $('#AddFund').click(function() {
//       $(this).submitAndMoveToLocation('fund_table')
//    })
//
//    if (window.location.hash == '#fund_table') {
//        $('#fund_table tr:last-child td').effect('highlight', {}, 1000);
//    }

});


$.fn.submitAndMoveToLocation = function(anchor, button) {
    //Get the closest form element to the changed element
    var callingElement = $(this);
    var form = $(this).closest('form');
    //Get the current action attribute
    var formUrl = form.attr('action');
    //Check to see if it already has a hash
    if (formUrl.indexOf('#') == -1) {
        //If not then add the anchor variable in as passed by the function and construct a new action attribute
        formUrl = formUrl + '#' + anchor;
        //Set the new attrib
        form.attr('action', formUrl);
        // set the button action
        $('#ajaxButton').val(button);
        //submit the form
        form.submit()
    }
}

var Cookies = {};

Cookies.get = function(name) {
    var start = document.cookie.indexOf(name + "=");
    var len = start + name.length + 1;
    if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return null;
    }
    if (start == -1) return null;
    var end = document.cookie.indexOf(';', len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len, end));
};

Cookies.set = function(name, value, expires, path, domain, secure) {
    var today = new Date();
    today.setTime(today.getTime());
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));
    document.cookie = name + '=' + escape(value) +
			((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
			((path) ? ';path=' + path : '') +
			((domain) ? ';domain=' + domain : '') +
			((secure) ? ';secure' : '');
};

Cookies.del = function(name, path, domain) {
    if (getCookie(name)) document.cookie = name + '=' +
		    ((path) ? ';path=' + path : '') +
		    ((domain) ? ';domain=' + domain : '') +
		    ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
};

var newPhoneNumber = null;

function replacePhoneNumber(current) {
    if (newPhoneNumber == null || current == newPhoneNumber) {
        return;
    }
    var chars = current.toString().split('');
    var pattern = '';
    var count = 0;
    var max = 500;

    $(chars).each(function() {
        if (this != ' ') {
            pattern += this + '\\s*';
        }
    });
    if (pattern.length > 3) {
        pattern = pattern.substring(0, pattern.length - 3);
    }
    var regEx = new RegExp(pattern);
    $('.main *, #main *').each(function() {
        if (count > max) {
            return;
        }
        try {
            if ($(this).children().length < 1) {
                $(this).text($(this).text().replace(regEx, newPhoneNumber));
            }
        } catch (e) {
        }
        count++;
    });

}

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");

        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return null;
}

function checkForPpcCampaignId(campaignSettingScriptPath) {
    // if the querystring has a campaign id
    var id = getQueryVariable("ppc");
    // write out a script tag with the ppc id appended to the url
    if (id != null && id != "") {
        document.write("<" + "scr"+"ipt type=\"text/javascript\" src=\"" + campaignSettingScriptPath + "?ppc=" + escape(id) + "\"></sc"+"ript>");
    }
}


