var $j = jQuery.noConflict();
//var tvSizes = [{ display: "19", url: "blah", id: '[sitecoreid]' }, { display: "40", url: "blah", id: '[sitecoreid]' }, ...];
var selector; var selectortext; var template;

$j(document).ready(function () {
    $j('ul.accordion a.heading, ul.accordion2 a.heading').click(function () {

        $j(this).css('outline', 'none');
        if ($j(this).parent().hasClass('current')) {
            var date = new Date();
            date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
            document.cookie = 'industry_collapsed=true;path=/;expires=' + date.toGMTString() + ';';
            $j(this).siblings('ul').slideUp('slow', function () {
                $j(this).parent().removeClass('current');
            });
        } else {
            var date = new Date();
            date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
            document.cookie = 'industry_collapsed=false;path=/;expires=' + date.toGMTString() + ';';
            $j(this).parent().children('li.current ul').slideUp('slow', function () {
                $j(this).parent().removeClass('current');
            });
            $j(this).siblings('ul').slideToggle('slow', function () {
                $j(this).parent().toggleClass('current');
            });
        }
        return false;
    });

    /* Allow focus in IE7 */
    var ua = $j.browser;
    if (ua.msie && ua.version <= 7) {
        $j('input, textarea')
            .bind('focus', function () {
                $j(this).addClass('focused');
            }).bind('blur', function () {
                $j(this).removeClass('focused');
            });
    }

    /* Setup WYSIWYG editors */
    $j('.jwysiwyg:enabled').wysiwyg({
        controls: {
            bold: { visible: true },
            italic: { visible: true },
            createLink: { visible: true }
        }
    });

    // ==========================================
    // Setup all input text box to clear on focus
    $j('input[type="text"], input[type="password"], textarea').each(function () {
        $j(this).CreateAutoSelect();
    });

    $j("#ddlContacts").change(function () {
        $j('input[type="text"], input[type="password"], textarea').each(function () {
            $j(this).CreateAutoSelect();
        });
        DrawForms();
    });

    $j(".triggersection input[type='text'], .triggersection input[type='password']").keypress(function (e) {
        if (e.which == 13) {
            e.preventDefault();
            var clickee = $j(this).parents('.triggersection').find('.triggered');
            if (clickee.attr('href') != null && clickee.attr('href') != "" && clickee.attr('href').indexOf('#') == -1) {
                location.href = clickee.attr('href');
            } else {
                clickee.click();
            }
            return false;
        }
    });

    $j(".formatphone").blur(function () {
        var val = $j(this).val();
        val = val.replace(/[^\d.]/g, "");
        if (val.length == 10) {
            val = "(" + val.substr(0, 3) + ") " + val.substr(3, 3) + "-" + val.substr(6);
            $j(this).val(val);
        }
    });

    $j(".formatpostalcode").blur(function () {
        var val = $j(this).val();
        if (val.length >= 6 && isNaN(val) && val.indexOf("-") == -1) {
            if (val.indexOf(" ") == -1) { val = val.substr(0, 3) + " " + val.substr(3); }
        }

        $j(this).val(val.toUpperCase());
    });

    /* Setup date pickers editors */
    $j('.datetimebox').datetimepicker({
        changeYear: true,
        changeMonth: true,
        dateFormat: 'MMM d yyyy h:mm tt'
    });
    $j('.datebox').datepicker({
        changeYear: true,
        changeMonth: true,
        dateFormat: 'M d yy'
    });

    $j('.dateicon').click(function (e) {
        e.preventDefault();
        var box = $j(this).parent().children('.datebox, .datetimebox');
        if (!box.is(':disabled')) {
            $j(this).parent().children('.datebox, .datetimebox').focus();
        }
        return false;
    });

    $j('.words-remaining-input').each(function () {
        var initialval = $j(this).find('.word-count').html();
        $j(this).parents('td').find('.box, .desc').keydown(function (e) {
            var rem = initialval - ($j(this).val().split(' ').length - 1);
            if (rem <= 0 && $j(this).getCursorPosition() == $j(this).val().length && e.which != 8) {
                return false;
            }
        });
        $j(this).parents('td').find('.box, .desc').keyup(function () {
            var rem = initialval - ($j(this).val().split(' ').length - 1);
            var currentval;
            while (rem < 0) {
                currentval = $j(this).val();
                $j(this).val(currentval.substr(0, currentval.lastIndexOf(' ')));
                rem = initialval - ($j(this).val().split(' ').length - 1);
            }
            if (rem == 0) {
                currentval = $j(this).val();
                $j(this).val(currentval.substring(0, currentval.lastIndexOf(' ') + 1));
            }
            $j(this).parents('td').find('.word-count').html(rem);
        });
    });

    $j(".extradates .daterange").each(function (index) {
        var startDate = $j(this).children(".dateform").children("div").children(".startdate");
        if (startDate.length == 0 || $j(startDate).val() == "Starts" || $j(startDate).val() == "") {
            $j(this).hide();
        }
    });

    $j(".extradates .adddatesbutton").show();
    $j(".extradates .adddates").click(function (e) {
        e.preventDefault();
        var firstHidden = $j(this).parents(".extradates").find(".daterange:hidden").first();
        firstHidden.show();
        if ($j(this).parents(".extradates").find(".daterange:hidden").length == 0) {
            $j(this).parent().hide();
        }
        return false;
    });

    $j(".extradates .removedate").click(function (e) {
        e.preventDefault();
        $j(this).parents('.daterange').hide();
        $j(this).parent().find("input").each(function () {
            var title = $j(this).attr('title');
            $j(this).val(title);
        });
        $j(this).parents(".extradates").find(".adddatesbutton").show();

        return false;
    });

    if (typeof (Page_ClientValidate) != "undefined") {
        AspPage_ClientValidate = Page_ClientValidate;
        Page_ClientValidate = Page_ClientValidateOverride;
    }

    $j('.update .validate').click(function (e) {
        ClearDefaultValues();
        if (!Page_ClientValidateOverride()) {
            e.preventDefault();
            ResetDefaultValues();

            Page_BlockSubmit = false;
            return false;
        }
    });
    $j('.update .preview').click(function (e) {
        e.preventDefault();
        var title = $j(".previewwindowtitle").html();

        //Lets clear any default values
        ClearDefaultValues();

        //Then we validate before showing the preview
        if (Page_ClientValidateOverride()) {
            $j(".update input[type='text']:not('.datebox'), .update input[type='radio']:checked, .update textarea, .update select").each(function () {
                var me = $j(this);
                var trParent = me.parents("tr");

                if (trParent.attr('class') != "") {
                    var itemval = "";
                    var item = $j('.previewwindow .' + trParent.attr('class'));
                    var itemlabel = $j('.previewwindow .' + trParent.attr('class') + 'label');
                    var itemend = $j('.previewwindow .' + trParent.attr('class') + 'etc');

                    if (me.prop('tagName').toUpperCase() == 'SELECT') {
                        var selected = me.children("option:selected");
                        if (selected.val() != "") { itemval = selected.text(); } else { itemval = ""; }
                    } else if (me.prop('tagName').toUpperCase() == 'INPUT' && me.attr('type').toUpperCase() == 'RADIO') {
                        itemval = $j.trim(me.parents('li').children("label").html());
                    } else {
                        itemval = me.val();
                    }
                    itemval = RemoveBad(itemval);

                    item.html(itemval);
                    if (item.prop('tagName') != undefined) {
                        if (item.prop('tagName').toUpperCase() == 'A') item.attr('href', itemval);
                    }
                    if (itemval == "") {
                        itemlabel.html("");
                        itemend.html("");
                    } else {
                        itemlabel.html(trParent.find(".label").html());
                    }
                }
            });

            var classname = ""; var datefields = "";
            $j(".update .dateform:visible").each(function () {
                if (classname == "") { var trParent = $j(this).parents("tr"); classname = trParent.attr('class'); $j('.previewwindow .' + classname + 'label').html(trParent.find(".label").html()); }

                var dateitem = RemoveBad($j(this).find('.startdate').val());
                if (dateitem != "") {
                    var end = "";
                    var endfield = $j(this).find('.enddate');
                    if (endfield.length > 0) end = RemoveBad(endfield.val());
                    if (end != "") { dateitem = dateitem + " to " + end + "<br />"; } else { dateitem = dateitem + "<br />"; }

                    datefields = datefields + dateitem;
                }
            });

            if (classname != "") {
                $j('.previewwindow .' + classname).html(datefields);
            }

            var activitiestitle = "";
            var activitiestext = "";
            var activitieslabel = "";
            $j(".update .activities").each(function () {
                var trParent = $j(this).parents("tr");
                activitieslabel = trParent.attr('class');
                activitiestitle = trParent.find(".label").html();
            });
            $j(".update .activities input:checked").each(function () {
                var activity = $j.trim($j(this).parent().children("label").html());
                activitiestext = activitiestext + activity + ", ";
            });
            if (activitiestext.length > 0) activitiestext = activitiestext.substr(0, activitiestext.length - 2);

            if (activitieslabel != "") {
                $j('.previewwindow .' + activitieslabel).html(activitiestext);
                $j('.previewwindow .' + activitieslabel + 'label').html(activitiestitle);
            }

            $j(".update .checkboxlist").each(function () {
                var checked = $j(this).find(':checked');
                if (checked.length > 0) {
                    var trParent = $j(this).parents("tr");
                    $j('.previewwindow .' + trParent.attr('class') + 'label').html(trParent.find(".label").html());
                    var checkeditems = "";
                    checked.each(function () {
                        checkeditems = checkeditems + $j('label[for="' + $j(this).attr('id') + '"]').html() + ", ";
                    });
                    checkeditems = checkeditems.substring(0, checkeditems.length - 2);
                    $j('.previewwindow .' + trParent.attr('class')).html(checkeditems);
                }
            });

            $j(".previewwindow span").each(function () {
                if ($j(this).html() == "") {
                    $j("." + $j(this).attr('class') + "etc").hide();
                    $j(this).hide();
                }
            });

            $j(".previewwindow").dialog({
                modal: true,
                resizable: false,
                width: 500,
                title: title,
                close: ResetDefaultValues
            });
        } else {
            ResetDefaultValues();
        }
        Page_BlockSubmit = false;
        return false;
    });

    $j('.ui-widget-overlay, .previewwindow .editbutton').live("click", function (e) {
        e.preventDefault();
        $j(".previewwindow").dialog("close");
        return false;
    });

    $j('select').change(function () {
        var txt = $j(this).children("option:selected").text();
        if (txt.length > 22) {
            txt = txt.substring(0, 19) + "...";
        }
        selectortext = txt;
        selector = $j(this);
        selector.parent().removeClass("errorinput");
        setTimeout("selector.parent().children('span:first').text(selectortext);", 0);
    });

    setTimeout("$j('.selector').addClass('fixie');", 0);

    //FAQ ACCORDION
    $j(".accordionContentBox h4").click(function () {
        if ($j(this).hasClass("active")) {
            $j(this).removeClass("active");
            $j(this).next("div").slideUp();
        } else {
            $j(this).next("div").slideDown();
            $j(this).addClass("active");
        }
    });


    if (typeof (Sys) != 'undefined') {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(UpdatepanelUpdate);
    }

    DrawForms();
    MarkErrors();
});

function Page_ClientValidateOverride(validationGroup) {
    var valid = AspPage_ClientValidate(validationGroup);

    if (!valid) {
        MarkErrors();
    }

    return valid;
}


function UpdatepanelUpdate() {
    //redraw forms
    DrawForms();
}

function ClearDefaultValues() {
    $j('.update input[type="text"], .update textarea').each(function () {
        if ($j(this).val() == $j(this).attr("title")) $j(this).val('');
    });

    template = $j(".previewwindow").html();
}

function ResetDefaultValues() {
    $j('.update input[type="text"], .update textarea').each(function () {
        if ($j(this).val() == '') $j(this).val($j(this).attr("title"));
    });

    $j(".previewwindow").html(template);
}

function MarkErrors() {
    $j('.inlineerror').each(function () {
        var style = $j(this).attr('style');
        if (typeof style == 'undefined' || style.indexOf('display: inline') > -1 || style.indexOf('visibility: visible') > -1) {
            $j(this).parent().find('input, textarea, .selector').addClass('errorinput');
        }
    });

    $j(".update .activities input[type='checkbox']").click(function () {
        $j(this).parents('td').find("input[type='checkbox']").removeClass("errorinput");
        $j(".update .activities input[type='checkbox']").unbind("click");
    });
}

function DrawForms() {
    $j("select, input:radio").each(
    function () {
        if(!$j(this).parents('div').is('.selector, .radio')) $j(this).uniform();
    });
}

function DeleteSelected(message) {
    var lstIds = "";
    $j(":checkbox:checked").each(function () {
        lstIds += $j(this).val() + ",";
    });
    lstIds = lstIds.slice(0, -1);

    $j("#hdnSelectedRows").val(lstIds);

    if (lstIds.length > 0) {
        return confirm(message);
    } else {
        return false;
    }
}

function RemoveBad(strTemp) {
    strTemp = strTemp.toUpperCase().replace(/<(SCRIPT|OBJECT|APPLET|EMBED|FORM){1}.*>/i, ''); 
    return strTemp;
} 

(function($j)
{
	$j.fn.CreateAutoSelect = function()
	{
		
	//  =============
	//  Global Object
		var global =
		{
			// Input box object
			inputBox: $j(this)
		};
		
	//  =================
	//  Initiate Function
		var jQueryAutoSelect = function()
		{
		    if(global.inputBox.val()=="") { global.inputBox.val(global.inputBox.attr('title')); }
		    
		    // When the input box is focused
			global.inputBox.focus(function()
			{
				// If the input box value is the default string
				// The input box is cleared allowing for direct input
				// Otherwise the value of the input box is selected
				(global.inputBox.attr('value') == global.inputBox.attr('title')) ? global.inputBox.attr('value', '') : global.inputBox.select();

                // Clear error
                global.inputBox.removeClass('errorinput');
			
			// When the input box loses its focus
			}).blur(function()
			{
				// If the input box value is blank when it loses focus
				// Reset the value to the default string
				if (global.inputBox.attr('value') == '') { global.inputBox.attr('value', global.inputBox.attr('title')); }
			});
		};
		
		// Initiate the auto selecting/clearing
		jQueryAutoSelect();
	};
})(jQuery);

(function ($) {
    $.fn.getCursorPosition = function () {
        var pos = 0;
        var el = $(this).get(0);
        // IE Support
        if (document.selection) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        // Firefox support
        else if (el.selectionStart || el.selectionStart == '0')
            pos = el.selectionStart;

        return pos;
    }
})(jQuery);



