﻿function confirmExternalLink(url) {
    if (confirm("If you would like to view this website, you may click on this link. It is important to note that by clicking on this link you will be leaving this website and the information viewed there is not the property of Claymore Investments, Inc.") == true) {
        window.open(url);
    }
    return false;
}
function confirmVideo(url) {
    if (confirm("The opinions expressed in the video are those of the participants and are subject to change at any time due to changes in market or economic conditions. The comments should not be construed as a recommendation of individual holdings or market sectors, but as an illustration of broader themes. The opinions in this video are not necessarily those of Claymore Investments or any of its affiliates and are not intended to be a forecast or guarantee of performance. Information in this video is not meant as a solicitation for any product. All investing involves risk and it is possible to lose money on an investment.") == true) {
        window.open(url);
    }
    return false;
}
(function($) {
    $.fn.extend({
        accordionCLCA: function() {
            return this.each(function() {
                if ($(this).data('accordiated'))
                    return false;
                $.each($(this).find('ul, li>div'), function() {
                    $(this).data('accordiated', true);
                    $(this).hide();
                });
                $.each($(this).find('a:not(.foo)'), function() {
                    $(this).click(function(e) {
                        activate(e.target);
                        return void (0);
                    });
                });

                var active = false;
                if (location.hash)
                    active = $(this).find('a[href=' + location.hash + ']')[0];
                else if ($(this).find('li.current'))
                    active = $(this).find('li.current a')[0];

                if (active) {
                    activate(active, 'toggle', 'parents');
                    $(active).parents().show();
                }

                function activate(el, effect, parents) {
                    $(el)[(parents || 'parent')]('li').toggleClass('active').siblings().removeClass('active').children('ul, div').slideUp('fast');
                    $(el).siblings('ul, div')[(effect || 'slideToggle')]((!effect) ? 'fast' : null);
                }

            });
        }
    });
})(jQuery);

$(document).ready(function() {
    var path = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
    if (path) {
        var oNavLnks = $('a[href$="' + path + '"]');
        if (oNavLnks.length == 1) {
            oNavLnks.attr('class', 'selected');
        }
        else {
            var fundNavLinks = $('#etfEducationSubNav ol li a[href$="' + path + '"]');
            if (fundNavLinks.length == 1) {
                // within product
                fundNavLinks.attr('class', 'selected');
            }
            else {
                // outside product - update all
                oNavLnks.attr('class', 'selected');
            }
        }
    }
});

// custom search box for Claymore
var ClaymoreSearchBox=function(txtSearchId, imgId, searchUrl, initSearchValue) {
	//var INIT_SEARCH_VALUE = "Search";
	var oSearchBox = $("#"+txtSearchId);
	
	var RunSearch=function(){
	    var textValue=oSearchBox.val();
	    if(textValue==="" || textValue===initSearchValue){
	        alert("Please input text into the Search box");
	    }
	    else{
	        location.href=searchUrl + "?s=" + escape(textValue);
	    }
	}
	
	var InitSearchBox=function(){
		if(txtSearchId){
			oSearchBox.focus(function(){
				if(this.value===initSearchValue){
					this.value="";
				}
			});
			oSearchBox.blur(function(){
				if(this.value===""){
					this.value=initSearchValue;
				}
			});
			oSearchBox.keypress(function(e){
			    var code = (e.keyCode ? e.keyCode : e.which);
			    if(code === 13){ // enter key
			        RunSearch();
			        e.preventDefault();
			    }
			});
			oSearchBox.autocomplete({
				// minLength : 2,
				source : function(request,response){
					var currentText=oSearchBox.val();
					if(currentText.indexOf(" ") < 0){
						$.ajax({
							type: "POST",
							url: "/WebServices/SiteSearchService.asmx/GetAutoCompleteResults",
							data: "{text: \"" + currentText + "\"}",
							contentType: "application/json; charset=utf-8",
							dataType: "json",
							dataFilter: function(data) {
								var msg = eval('(' + data + ')');
								if (msg.hasOwnProperty('d'))
								  return msg.d;
								else
								  return msg;
							},
							success: function(results) {
								response(results);
							}
						});
					}
					else{
						response([]);
					}
				},
				select:function(event,ui){
					if(ui.item.value.length > 0){
						RunSearch();
					}
				}
			});
		}
		if(imgId){
		    $("#"+imgId).click(RunSearch);
		}
	}
	
	InitSearchBox();
	
	return {}
};

// Ask the CEO form
var AskTheCEOForm = function(ceoCornerUrl) {
    var _lnkRecentId = "lnkAskTheCEORecent", _txtEmailId = "txtAskTheCEOEmail";
    var _txtComments = "txtAskTheCEOComments", _lnkSubmit = "lnkAskTheCEOSubmit";
    var _divResultId = "divResult", _resultDivAdded = false;
    var LOADING_HTML = "<img src=\"/Common/images/loading.gif\"> Loading...</a>";
    var SENT_SUCCESS_HTML = "<div style=\"font-weight:bold;color:#4AA63A;font-size:13px;\">Email Sent</div>";

    var SubmitEmail = function() {
        var emailAddress = $.trim($("#" + _txtEmailId).val());
        var comments = $.trim($("#" + _txtComments).val());

        if (emailAddress.length > 0 && comments.length > 0) {
            comments = comments.replace(/\\/g, "\\\\").replace(/\"/g, "\\\"");
            SetResultDiv(LOADING_HTML);

            $.ajax({
                type: "POST",
                url: "/WebServices/AskTheCEOService.asmx/SendAskTheCEOComment",
                data: "{emailAddress: \"" + emailAddress + "\", comment: \"" + comments + "\"}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                dataFilter: function(data) {
                    var msg = eval('(' + data + ')');
                    if (msg.hasOwnProperty('d'))
                        return msg.d;
                    else
                        return msg;
                },
                success: function(results) {
                    SubmitEmailSuccess(results);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    SubmitEmailSuccess();
                }
            });
        }
    }
    var SubmitEmailSuccess = function(result) {
        SetResultDiv(SENT_SUCCESS_HTML);
    }
    var SetResultDiv = function(html) {
        if (!_resultDivAdded) {
            $("#" + _lnkSubmit).after("<div id=\"" + _divResultId + "\"></div>");
            _resultDivAdded = true;
        }
        $("#" + _lnkSubmit).hide();
        $("#" + _divResultId).html(html);
    }   

    var Init = function() {
        $("#" + _lnkSubmit).click(SubmitEmail);
        $("#" + _lnkRecentId).attr("href",ceoCornerUrl);
        /*$("#" + _lnkRecentId).click(function() {
            location.href = ceoCornerUrl; // go to CEO corner page
        });*/
    }

    Init();
    return {};
};


// custom login for Claymore
var ClaymoreUserLogin = function(useHttps, userTxtId, passwordTxtId, imageBtnId, isRegisterPage) {
    //var SERVICE_URL_RELATIVE_URL = "/WebServices/UserLoginService.asmx/LoginUser";
    var LOGIN_SUBMIT_RELATIVE_URL = "/common/aspx/UserLoginSubmit.aspx";
	var _isSubmitting=false;

    var SubmitUsernameAndPassword = function() {
		if(!_isSubmitting){
			_isSubmitting = true;
			
			var username = $("#"+userTxtId).val();
			var password = $("#"+passwordTxtId).val();
			
			// add new form to the new page
			var submitUrl = GetSubmitUrl();
			var formId = "frmClaymoreUserLogin";
			
			var formHtml = '<form action="' + submitUrl + '" method="post" name="'+formId+'" id="'+formId+'">';
			formHtml+= '<input type="hidden" name="emailAddress" value="' + username + '">';
			formHtml+= '<input type="hidden" name="isRegisterPage" value="' + isRegisterPage + '">';
			formHtml+= '<input type="hidden" name="password" value="' + password + '"></form>';
			
			$("body").append(formHtml);
			
			// submit the new form
			var oFrm=$("form#"+formId);
			oFrm.submit();
        }
        /**
        var redirectUrl = window.location.pathname;
        var serviceUrl = GetServiceUrl();

        $.ajax({
            type: "POST",
            url: serviceUrl,
            data: "{emailAddress: \"" + username + "\", password:\"" + password + "\", redirectUrl:\"" + redirectUrl + "\"}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            dataFilter: function(data) {
                var msg = eval('(' + data + ')');
                if (msg.hasOwnProperty('d'))
                    return msg.d;
                else
                    return msg;
            },
            success: function(result) {
                if (result && result.IsSuccess && result.RedirectUrl) {
                    location.href = result.RedirectUrl;
                }
                else {
                    $("#login-err").show();
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) { }
        });
        **/
    }
    
    
	var GetSubmitUrl=function(){	
		var currentUrl=location.href;
		var serviceUrl = LOGIN_SUBMIT_RELATIVE_URL;
		if(currentUrl.indexOf("http://")>=0){
			// look for host value between second and third slash
			var ix=currentUrl.indexOf("/",0);
			var ix2=currentUrl.indexOf("/",ix+1);
			var ix3=currentUrl.indexOf("/",ix2+1);
			if(ix3>0){
				var host=currentUrl.substring(ix2+1,ix3); 
				serviceUrl = (useHttps ? "https" : "http") + "://" + host + LOGIN_SUBMIT_RELATIVE_URL;
			}
			
		}
		return serviceUrl;
	};

    /*var GetServiceUrl = function() {
        var currentUrl = location.href;
        var serviceUrl = SERVICE_URL_RELATIVE_URL;
        if (currentUrl.indexOf("http://") >= 0) {
            // look for host value between second and third slash
            var ix = currentUrl.indexOf("/", 0);
            var ix2 = currentUrl.indexOf("/", ix + 1);
            var ix3 = currentUrl.indexOf("/", ix2 + 1);
            if (ix3 > 0) {
                var host = currentUrl.substring(ix2 + 1, ix3);
                serviceUrl = (useHttps ? "https" : "http") + "://" + host + SERVICE_URL_RELATIVE_URL;
            }
        }
        return serviceUrl;
    }*/

    var CheckForEnter = function(e) {
        if (e.which == 13) { // enter key
            SubmitUsernameAndPassword();
            return false;
        }
    }

    /*var HideMsg = function() {
        $("#login-err").fadeOut(1000);
    }*/

    var CollapseLoginDropDown = function() {
        $(".loginDropdown").slideUp(200);
        $("#playPause").attr("src", "/common/images/advAroDown.gif");
    }

    var OpenLoginDropDown = function() {
        $(".loginDropdown").slideDown(200);
        $("#playPause").attr("src", "/common/images/advAroUp.gif");
    }

    var Init = function() {
        $("#"+userTxtId+", #"+passwordTxtId).keypress(CheckForEnter);
        $("#"+imageBtnId).click(SubmitUsernameAndPassword);
        if(!isRegisterPage){
			$("#logindd").click(function() {
				var reg = new RegExp("advAroUp.gif$");
				var isOpen = reg.test($("#playPause").attr("src"));
				if (isOpen){
					CollapseLoginDropDown();
				}
				else{
					OpenLoginDropDown();
				}
			});
        }
    }

    Init();
    return {};
};