/*
* jQuery replaceText - v1.1 - 11/21/2009
* http://benalman.com/projects/jquery-replacetext-plugin/
* 
* Copyright (c) 2009 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($) { $.fn.replaceText = function(a, b, c) { return this.each(function() { var e = this.firstChild, g, d, f = []; if (e) { do { if (e.nodeType === 3) { g = e.nodeValue; d = g.replace(a, b); if (d !== g) { if (!c && /</.test(d)) { $(e).before(d); f.push(e) } else { e.nodeValue = d } } } } while (e = e.nextSibling) } f.length && $(f).remove() }) } })(jQuery);

// Web Teks added function to run JS after all other JS
	function addLoadEvent(func) { 
	  var oldonload = window.onload; 
	  if (typeof window.onload != 'function') { 
	    window.onload = func; 
	  } else { 
	    window.onload = function() { 
	      if (oldonload) { 
	        oldonload(); 
	      } 
	      func(); 
	    } 
	  } 
	} 

function removeAdminPort(link) {
    var rootURL = "www.iccsafe.org";

    var correctedURL = link.href.replace(":8888", "");
    correctedURL = correctedURL.replace("cch-web-sp.iccsafe-int.org", rootURL);
    correctedURL = correctedURL.replace("cch-web-sp", rootURL);
    correctedURL = correctedURL.replace("preview.iccsafe.org", rootURL);
    //    correctedURL = correctedURL.replace("65.201.76.66",rootURL);

    return correctedURL;
}

function removeAdminPortImg(img) {
    var rootURL = "www.iccsafe.org";

    var correctedURL = img.src.replace(":8888", "");
    correctedURL = correctedURL.replace("cch-web-sp.iccsafe-int.org", rootURL);
    correctedURL = correctedURL.replace("cch-web-sp", rootURL);
    correctedURL = correctedURL.replace("preview.iccsafe.org", rootURL);
    //    correctedURL = correctedURL.replace("65.201.76.66",rootURL);

    return correctedURL;
}



function generateEmLink(obj) {




    var unm = obj.name;

    var subject = "";
    if (obj.title.length > 0)
        subject = "?subject=" + obj.title;


    switch (obj.id) {
        case "ICC": dmn = "iccsafe.org"; break;
        case "IAS": dmn = "iasonline.org"; break;
        case "ES": dmn = "icc-es.org"; break;

        default: dmn = obj.id;
    }

    var asgn = "@";

    var adres = unm + asgn + dmn;

    return 'ma' + 'ilto:' + adres + subject;

}



function iccFinalizePage(url) {

    if (!url || "" == url) {
        url = document.URL;
    }


    if (url.indexOf(":8888") == -1) {
        $("a[href*=':8888'],a[href*='cch-web-sp']").each(function() {
            $(this).attr("href", removeAdminPort(this))
        });


        // SSO Sign Out
        $("a:contains('Sign Out')[href*='$LoginView$']").click(function() {
            var href = $(this).attr("href");
            $(document.body).append('<IFRAME id="eWebLogout" width="1" height="1"></IFRAME>');
            var iframe = $('iframe#eWebLogout');
            iframe.load(function() {
                window.location = href;
            });
            iframe.attr('src', 'https://av.iccsafe.org/eweb/Logout.aspx?Site=icc');
            return false;
        });
        
     $("table[class='ms-siteaction']").css("display", "none");
    }


    if (url.indexOf("NewForm.aspx") >= 0) {
        //Override the behavior of the Cancel button to go "back" when clicked

        $(function() { $("input[value='Cancel']").live("click", function() { history.go(-1); return false }) });
    }


    // generate email addresses
    $(".emLink").click(function() {
        $(this).attr("href", generateEmLink(this))
    });


    // fix the ad rotator on the home page
    $("#ctl00_m_g_f78e82cd_52d4_47c9_8399_d0e1f42392b7").css("padding-left", "28px");


    // two fixes to allow an anonymous user to get to an Event Calendar entry - our custom form
    if (url.indexOf("/Pages/events.aspx") >= 0) {
        $("#MontlyViewDefault_CalendarView a,td[href]").each(function() {
            $(this).attr("href", this.href.replace("/Lists/EventCalendar/DispForm.aspx?", "/Pages/event.aspx?event"))
        });

    }

    if (url.indexOf("/Pages/events-list.aspx") >= 0) {
        $("a").each(function() {
            $(this).attr("href", this.href.replace("/Lists/EventCalendar/DispForm.aspx?", "/Pages/event.aspx?event"))
        });

    }



    // fix to allow an anonymous user to access Course Catalog detail page
    if (url.indexOf("/Education/Courses/Pages/catalog.aspx") >= 0) {
        $("a").each(function() {
            $(this).attr("href", this.href.replace("/Lists/Catalog/DispForm.aspx?", "/Pages/course.aspx?course"))
        });

    }


    // fix to remove "Other" sites from breadcrumb
    if (url.indexOf("/content/Pages/") >= 0) {
        $(".ms-sitemapdirectional").each(function() {
            if ($(this).attr("href").indexOf("/content/Pages") >= 0) {
                $(this).css("display", "none");
                $(this).parent().next().css("display", "none");
            }
        });

    }


    //fix to remove "No Product ID for URL" message from Education live schedule detail page
    if (url.indexOf("/Education/Courses/Lists/Schedule/DetailForm.aspx") >= 0) {
        $("#ctl00_m_g_025de323_ecd7_4ec3_b00c_e04dfd046da2").css("display", "none");
    }

	// Agile: modification of image link on free ecodes, if not logged in, send user to optional survey
	// Modified by Web Teks to perform the same for title links
    if (url.indexOf("/Store/Pages/FreeCodes.aspx") >= 0 && $(".loginBoxFields").length) {
        $("table.ms-listviewtable td.ms-vb2 a").live("click", function() {
            $(this).attr("href", "/Store/Pages/eCodesOptionalSurvey.aspx?Source=%2FStore%2FPages%2FeCodesLauncher.aspx%3FSource%3D" + encodeURIComponent(encodeURIComponent(this.href)));
            $(this).attr("target", "");
        });
    }


    if (url.indexOf("/Store/Pages/eCodesLauncher.aspx") >= 0) {
        $("a#redirect").attr("href", decodeURIComponent(location.search.substring(8)));
        $("a#redirect2").attr("href", decodeURIComponent(location.search.substring(8)));
    }

    //fix to remove link to AllItems.aspx on new member app form, and to change the title on that page
    //and temp fix: change Contact Name to Last Name for Retired Members
    if (url.indexOf("/Membership/Lists/ICCSafeMember/NewForm.aspx") >= 0) {
        $("h2.ms-pagetitle").html("New Member Application Form");
        $("nobr:contains('Contact Name')").text("Last Name");
    }


    //fix to remove link on chapterEvents.aspx
    if (url.indexOf("/Education/Courses/Pages/chapterevents.aspx") >= 0) {
        $("a").each(function() {
            if ($(this).attr("href").indexOf("/gr/Lists/") >= 0) {
                $(this).attr("href", "#");
            }
        });
    }

    //fix to continue button on register.aspx
    if (url.indexOf("/Pages/register.aspx") >= 0) {
        var continueButton = $(":submit[id$='_ContinueButtonButton']");
        var returnUrl = GetUrlKeyValue("ReturnUrl", false);
        if (null != continueButton && "" != returnUrl) {
            continueButton.click(function() {
                window.location.href = returnUrl;
                return false;
            });
        }
    }



    // temporary fix promo URLs
    if (url.indexOf("/NotFound.aspx") >= 0) {
        var decodeurl = decodeURIComponent(url).replace("&#061 ", "=");
        var searchvalue = "&k=promo.html?promoid";
        var index = decodeurl.indexOf(searchvalue);
        if (index != -1) {
            var code = jQuery.trim(decodeurl.substring(index + searchvalue.length + 1));
            var href = "/Store/Pages/AddToCartRedirect.aspx?Coupon=@&RedirectUrl=/Store/Pages/@.aspx".replace(/@/g, code);
            $("div[class='smart404'] h2").text("The page you requested has been moved");
            $("div[class='smart404Notice']").html("The page you requested has been moved, <a href='" + href + "'>access the new page here</a>.");
            $("div[class='smart404Return']").hide();
            window.location.replace(href);
        }
    }


    //Hide Links from MySite Left Nav: Lists, Discussions, Surveys and Sites
    if (url.indexOf("/ICCPersonal/") >= 0 || url.indexOf("/MySite/") >= 0) {
        $("#zz2_QuickLaunchMenun10").css("display", "none");
        $("#zz2_QuickLaunchMenun11").css("display", "none");
        $("#zz2_QuickLaunchMenun12").css("display", "none");
        $("#zz2_QuickLaunchMenun13").css("display", "none");
    }


    // temporary fix to rename Course ID to Course Title
    if (url.indexOf("/Education/Courses/Lists/Requests/NewForm.aspx") >= 0) {
        $("nobr:contains('Course ID')").contents()[0].nodeValue = "Course Title";
    }

    // temporary fix to change href on Member Logo link on My ICC page
    if (url.toLowerCase().indexOf("/myicc/pages/default.aspx") >= 0) {	
        $("a").each(function() {
            $(this).attr("href", this.href.replace("/Membership/Lists/ICC%20Member%20Logo%20Request/NewForm.aspx", "/Membership/Pages/logo-member.aspx"))
        });
    }


    // temporary fix to show a message on the cart.aspx for users who have a coupon (remove after release 1.5)
    if (url.toLowerCase().indexOf("/store/pages/cart.aspx") >= 0) {
	var CouponCodeInput = $(":input[name='PromoCode']");
        if (CouponCodeInput.val() != undefined) {
	    if (CouponCodeInput.val() != "")
		    $("#CouponMessage").css({'display' : 'block'});
        }
    }


    // temporary fix redirect users off of the NTLM version of the cart.aspx page if they should be on FBA site
    if (url.toLowerCase().indexOf(":8888/store/pages/cart.aspx") >= 0) {
	var SignInLink = $("a[class='loginWelcome']").attr("href");
	if (SignInLink != undefined)
		window.navigate("http://www.iccsafe.org/Store/Pages/Cart.aspx");
    }
	
	// Web Teks Added: trimming of eCodes Product ID on product details pages to shorter Product ID similar to regular products
	if (($('page').context.title.toLowerCase().indexOf("download") >= 0) && (url.toLowerCase().indexOf("/store/pages/product.aspx") >= 0))  	{
		var regex = / (.*?)_/;
		var matches = regex.exec($('.ProductId').html());
		var text = matches[1];
	
		$('.ProductId').html('Product '+text+'<br />');
	};
	
	// Web Teks Added: Trimming of longer eCodes Product IDs from cart.aspx page
	if (url.toLowerCase().indexOf("/store/pages/cart.aspx") >= 0)  {
		var regex = /(.*?)_/;
		var itemSpans = $('#ProductId span.Value');
		for (var i=0; i <itemSpans.length; i++) {
			var newText = regex.exec($('#ProductId span.Value')[i].innerHTML);
			if (newText != null) {
				$('#ProductId span.Value')[i].innerHTML = newText[1];
			}
		}
	}
	// Web Teks Added: Renaming of cancel link on optional survey page
	if (url.toLowerCase().indexOf("/store/pages/ecodesoptionalsurvey.aspx") >= 0)  {
		document.getElementById('ctl00_m_g_0c4a7dbd_4e6e_49b9_9634_65dc6b9b8b6f_gobackbutton1_ctl00_diidIOGoBack').value = "Skip Survey";
		document.getElementById('ctl00_m_g_0c4a7dbd_4e6e_49b9_9634_65dc6b9b8b6f_gobackbutton2_ctl00_diidIOGoBack').value = "Skip Survey";
	}
	
	// Web Teks Added: Google Analytics tracking of purchases where visitor has visited the Education Section
	if (url.toLowerCase().indexOf("/education/") >= 0)  {
		addLoadEvent(pageTracker._trackEvent('SitePurchaseTracking', 'Education Section'));
	}
}
_spBodyOnLoadFunctionNames.push("iccFinalizePage");

// Web Teks added: temporary fix hiding Availability Heading from final confirmation page of check out (uses jQuery Library)
function hideAvailability() {
    if (url.toLowerCase().indexOf("/store/pages/checkout.aspx") >= 0) {
		$('th').each(function() { if (/availability/i.test($(this).html())) { $(this).hide(); } });
	}
	if (url.toLowerCase().indexOf("/store/pages/cart.aspx") >= 0) {
		$('div').each(function() { if (/availability/i.test($(this).attr('id'))) { $(this).hide(); } });
	}
}
addLoadEvent(hideAvailability);

// Web Teks added: trigger GA tracking based on URL variables
var GETDATA = new Array();
var sGet = window.location.search;
if (sGet) 
{
    sGet = sGet.substr(1);
    var sNVPairs = sGet.split("&");
    for (var i = 0; i < sNVPairs.length; i++)
    {
        var sNV = sNVPairs[i].split("=");
        var sName = sNV[0];
        var sValue = sNV[1];
        GETDATA[sName] = sValue;
    }
}
function fireEvent(cat, act, lab) {
	if (lab == undefined) {
		pageTracker._trackEvent(cat, act);		
	}
	pageTracker._trackEvent(cat, act, lab);
}
if (GETDATA["r"] != undefined)
{
	addLoadEvent(fireEvent('Redirect Tracking',GETDATA["r"]));
}
if (GETDATA["afid"] != undefined)
{
	addLoadEvent(fireEvent('Affiliate Tracking',GETDATA["afid"]));
}
if (GETDATA["ebn"] != undefined)
{
	addLoadEvent(fireEvent(GETDATA["ebn"],GETDATA["ebd"],GETDATA["ebl"]));
}

