var TM = {}; //tellme namespace

jQuery(function(){
    var accordian = new TM.Accordian();
    var fbForm = new TM.FeedbackForm();
});

TM.Accordian = function(){
    var self = this; //scope adjustment

    this.init = function(){
        self.initEvents();
        self.showSectionOnLoad();
    };

    this.initEvents = function(){
        //add expand and close event listeners
        $('.expand').live('click', function(event){
            event.preventDefault();
            self.expand.call(this);
        });

        $('.close').live('click', function(event){
            event.preventDefault();
            self.close.call(this);
        });
    };

    this.expand = function(){
        //close the currently expanded section
        var curExpanded = $('.sect.expanded');
        if(curExpanded.length > 0){
            curExpanded.find('.details').slideUp();
            curExpanded.removeClass('expanded');
            curExpanded.find('.close')
                .html('Details and Downloads')
                .removeClass('close')
                .addClass('expand');
        }
        $(this).prev('.details').slideDown();

        //change the classname and text of the link to "close"
        $(this)
            .removeClass('expand')
            .addClass('close')
            .html('Close');

        $(this).closest('.sect').addClass('expanded');
    };

    this.close = function(){
        $(this).prev('.details').slideUp();

        //change the classname and text of the link to "details and downloads"
        if ($(this).closest('.sect').attr('id') == 'webcasts') {
            $(this).html('Expand');
        }
        else {
            $(this).html('Details and Downloads');
        }
        $(this)
            .removeClass('close')
            .addClass('expand')
        ;

        $(this).closest('.sect').removeClass('expanded');
    };

    //if the user goes to the url with an anchor pointing to a specific section, show that section expanded
    this.showSectionOnLoad = function(){
        var uri = window.location.href;
        if(uri.indexOf('#') != -1){
            var sect = '#' + uri.split('#')[1];
            if($(sect).length > 0){
                $(sect).find('.details').show();

                $(sect)
                .addClass('expanded')
                .find('.expand')
                    .removeClass('expand')
                    .addClass('close')
                    .html('Close');
            }
        }
    };


    this.init();
};

// Feedback Form Handling
TM.FeedbackForm = function (){
    var self = this;
    var link = undefined;
    var url  = "/about/contact_us/ajax";

    this.init = function(){
        self.initEvents();
    }

    this.initEvents = function(){
        $(".closeform").bind("click", function(){self.hideForm()});
        $(".protected").bind("click", function(){return self.doDownload($(this).attr("href"))});
        $("form").submit(function(){if (self.validate()) self.submit(); return false;});
    }

    this.getCookie = function(c_name){
        if (document.cookie.length>0)
        {
          c_start=document.cookie.indexOf(c_name + "=");
          if (c_start!=-1)
          {
              c_start=c_start + c_name.length+1 ;
              c_end=document.cookie.indexOf(";",c_start);
              if (c_end==-1) c_end=document.cookie.length
                return unescape(document.cookie.substring(c_start,c_end));
              }
        }
        return "";
    }

    this.setCookie = function(c_name,value,expiredays){
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : "; expires="+exdate.toGMTString());
    }

    this.doDownload = function(path){
        // Simple function.  If they have the cookie (or read this and create a cookie on their own :) don't show registration form
        var cookie = self.getCookie('tellmeDownload');
        if (cookie != null && cookie != "")
            return true;
        self.link = path;
        self.showForm();
        return false;
    }

    this.validate = function(){
        var success = true;
        // Make sure none of the required fields are empty... note submit is included but non-empty so it's ok
        $("form input").each(
            function ( i )
            {
                if ( $(this).val() == "" )
                {
                    $("form").find("#"+this.name+"Error").show();
                    success = false;
                } else {
                    $("form").find("#"+this.name+"Error").hide();
                }
            }
        );
        $("form select").each(
            function ( i )
            {
                if ( $(this).val() == "empty" )
                {
                    $("form").find("#"+this.name+"Error").show();
                    success = false;
                } else {
                    $("form").find("#"+this.name+"Error").hide();
                }
            }
        );
        //validate email
        var RE_EMAIL = /^(\w+\.)*\w+@(\w+\.)+[A-Za-z]+$/;
        if(($("#email").val() != "") && (!RE_EMAIL.test($("#email").val())))
        {
            $("#emailValidationError").show();
            success = false;
        } else {
            $("#emailValidationError").hide()
        };
        return success;
    }

    this.submit = function(){
        self.hideForm();
        $.post(url , $("form").serialize(),
            function(data,statustext) { if (statustext == 'success') { self.setCookie('tellmeDownload', '1', 180); location.href = self.link; } else { $.post(url,$("form").serialize()); } }
        );
    }

    this.showForm = function(){
        $(".formcontainer").show();
    }

    this.hideForm = function(){
        $(".formcontainer").hide();
    }

    this.init();
};
