﻿var urlParams = {};

function getUrlParams() {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
        urlParams[d(e[1])] = d(e[2]);
}

function InitSearchPage(coursetype) {

    $(document).ready(function () {
        getUrlParams();

        var selectedDate = urlParams["datestart"] == null ? "" : urlParams["datestart"];
        var dateType = urlParams["dateType"] == null ? 1 : urlParams["dateType"];
        //load refined search
        var elem_refined_search = $("div.refine_div");
        InsertLoadingGIF(elem_refined_search);
        $.ajax({
            type: "GET",
            url: "/controls/courserefinedsearch",
            data: { "url": window.location.href, "courseType": coursetype },
            contentType: "application/json; charset=utf-8",
            dataType: "html",
            success: function (data) {

                document.getElementById('c_refined_search').innerHTML = data;

                $(".refine_categories,.refine_organizers").ufd({ infix: false, height: "25px" });
                $(".refine_categories").removeAttr('disabled');
                $("#ZipCode").watermark("Enter ZIP Code");
                $(".date_range_div #DateStart").datepicker({
                    changeMonth: true,
                    changeYear: true,
                    showOtherMonths: true,
                    onSelect: function (dateStr) {
                        $(".date_range_div #DateEnd").datepicker('option', 'minDate', $(this).datepicker('getDate') || '-1m');
                    }
                });
                $(".date_range_div #DateEnd").datepicker({
                    changeMonth: true,
                    changeYear: true,
                    showOtherMonths: true,
                    onSelect: function (dateStr) {
                        $(".date_range_div #DateStart").datepicker('option', 'maxDate', $(this).datepicker('getDate') || 0);
                    }
                });
                $('#ui-datepicker-div').wrap('<div class="hasDP"></div>');

                //highlight custom date 
                var dateRangeLink = $('div.custom_date_range a');
                dateRangeLink.live('click',
                function (e) {
                    e.preventDefault();
                    var dateRangeLink = $('div.custom_date_range a');
                    var dateRangeDiv = $('div.date_range_div');
                    dateRangeLink.addClass("selected");
                    dateRangeDiv.show();
                    $('.ul_datefilter a.selected').removeClass('selected');
                });

                if (dateType == 7) {
                    var dateRangeLink = $('div.custom_date_range a');
                    var dateRangeDiv = $('div.date_range_div');
                    dateRangeLink.addClass("selected");
                    dateRangeDiv.show();
                }
            }
        });

        //load calendar
        InitCalendar(0, coursetype);

        $(".wide").watermark("Search keywords: Courses, Seminars, Training");
    });
}

function InsertLoadingGIF(elem) {
    elem.html("<div id=\"loadingGIF\"><img src=\"/content/images/loader.gif\"/></div>");
}

function RemoveLoadingGIF() {
    var loadingGIF = $("span[id*='loadingGIF']");
    loadingGIF.remove();
}

function ShareCourse(courseid) {
    $(document).ready(function () {
        //Examples of how to assign the ColorBox event to elements
        var ajaxDialog = $('div#ajaxDialog');

        //check if ajax dialog exist
        if (ajaxDialog.length == 0) {
            var body = $('body');
            body.append('<div id="ajaxDialog" style="display:none"></div>');
            ajaxDialog = $('div#ajaxDialog');
            InsertLoadingGIF(ajaxDialog);

            //create share dialog
            ajaxDialog.dialog({
                autoOpen: false,
                resizable: false,
                draggable: false,
                width: '575px',
                height: 'auto',
                title: 'Share Course'
            });

            //open share dialog
            ajaxDialog.dialog('open');

            //get share course form
            $.ajax({
                type: "GET",
                url: "/courses/sharecourse",
                data: { "courseid": courseid },
                contentType: "application/json; charset=utf-8",
                dataType: "html",
                success: function (data) {
                    //insert share form to div
                    ajaxDialog.html(data);

                    //close and open dialog to reposition dialog
                    ajaxDialog.dialog('close');
                    ajaxDialog.dialog('open');

                    //add close event handler
                    ajaxDialog.dialog('option', 'close',
                        function (event, ui) {
                            $(this).dialog('destroy');
                            $(this).remove();
                        });

                    //add click event handler for close button
                    var close = $('input#closeButton');
                    close.click(function () {
                        ajaxDialog.dialog('close');
                        ajaxDialog.dialog('destroy');
                        ajaxDialog.remove();
                    });
                }
            });
        }
        else {
            ajaxDialog.dialog('open');
        }
    });
    return false;
}

function closeAjaxDialog() {
    var ajaxDialog = $('div#ajaxDialog');
    if (ajaxDialog.length > 0) {

        //open share dialog
        ajaxDialog.dialog('close');
    }
}

function createErrorDialog(title, errorMessage) {

    var err = $('<div class="errMessage">');

    err.html(errorMessage);
    err.dialog({
        resizable: false,
        draggable: false,
        width: '500px',
        height: '110',
        title: title,
        buttons: {
            "Okay": function () {
                $(this).dialog("close");
                $(this).dialog("destroy");
            }
        },
        close: function (event, ui) {
            $(this).dialog('destroy');
            $(this).remove();

            var existingErr = $('div.errMessage');
            if (existingErr.length == 0) {
                //enable disabled buttons
                var buttons = $('.form_buttons input.form_disabled');
                buttons.removeAttr('disabled');
                buttons.toggleClass('form_disabled');
            }
        }
    });
}

function InitShareCourseForm(courseid) {
    var options = {
        dataType: 'json',
        success: showResponseDialog,  // post-submit callback 
        beforeSubmit: validateAjaxForm,
        data: { 'courseid': courseid }
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 

        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    };

    $('#ajax_form').ajaxForm(options);
}
function showResponseDialog(data) {
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 

    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 

    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server

    if (data.Succeed == true) {
        //close share dialog
        closeAjaxDialog();
    }
    //show notification to user that message has been sent
    createErrorDialog(data.Title, data.Message);
}

function validateAjaxForm(formData, jqForm, options) {
    // formData is an array of objects representing the name and value of each field 
    // that will be sent to the server;  it takes the following form: 
    // 
    // [ 
    //     { name:  username, value: valueOfUsernameInput }, 
    //     { name:  password, value: valueOfPasswordInput } 
    // ] 
    // 
    // To validate, we can examine the contents of this array to see if the 
    // username and password fields have values.  If either value evaluates 
    // to false then we return false from this method.

    var submit = $('.form_buttons input[type="submit"], .ajax_form button[type="submit"]');

    submit.attr('disabled', 'disabled');
    submit.toggleClass('form_disabled');

    //insert validation logic here


    //    for (var i = 0; i < formData.length; i++) {
    //        if (!formData[i].value) {
    //            alert('Please enter a value for both Username and Password');
    //            return false;
    //        }
    //    }
    //    alert('Both fields contain values.');

}


function AddCourseToCalendar(courseid) {
    $(document).ready(function () {
        $.post("/courses/addcoursetocalendar",
            { "courseid": courseid },
            function (data) {
                if (data.Succeed == true) {
                    createErrorDialog("Add to Calendar", "This course was added to your calendar.");
                }
                else {
                    createErrorDialog(data.Title, data.Message);
                }
            },
            "json"
        );

    });
    return false;
}

InquiryType = {
    Course: 1,
    Partner: 2
};

function showInquiryForm(id, inquiryType) {
    if (inquiryType == undefined ||
        (inquiryType != InquiryType.Course && inquiryType != InquiryType.Partner)) {
        type = InquiryType.Course;
    }

    $(document).ready(function () {
        //Examples of how to assign the ColorBox event to elements
        var ajaxDialog = $('div#ajaxDialog');

        //check if ajax dialog exist
        if (ajaxDialog.length == 0) {
            var body = $('body');
            body.append('<div id="ajaxDialog" style="display:none"></div>');
            ajaxDialog = $('div#ajaxDialog');
            InsertLoadingGIF(ajaxDialog);

            //create share dialog
            ajaxDialog.dialog({
                autoOpen: false,
                resizable: false,
                draggable: false,
                width: '600px',
                height: 'auto',
                title: 'Inquire'
            });

            //open share dialog
            ajaxDialog.dialog('open');

            var url = "/ajaxforms/inquiry";
            var ajaxData = { "id": id, "inquiryType": InquiryType.Course };

            if (inquiryType == InquiryType.Partner) {
                ajaxData = { "id": id, "inquiryType": InquiryType.Partner };
            }
            //get share course form
            $.ajax({
                type: "GET",
                //                url: "/courses/inquirecourse",
                //                data: { "courseid": id },
                url: url,
                data: ajaxData,
                contentType: "application/json; charset=utf-8",
                dataType: "html",
                success: function (data) {
                    //insert share form to div
                    ajaxDialog.html(data);

                    //close and open dialog to reposition dialog
                    ajaxDialog.dialog('close');
                    ajaxDialog.dialog('open');

                    //add close event handler
                    ajaxDialog.dialog('option', 'close',
                        function (event, ui) {
                            $(this).dialog('destroy');
                            $(this).remove();
                        });

                    //add click event handler for close button
                    var close = $('input#closeButton');
                    close.click(function () {
                        ajaxDialog.dialog('close');
                        ajaxDialog.dialog('destroy');
                        ajaxDialog.remove();
                    });
                }
            });
        }
        else {
            ajaxDialog.dialog('open');
        }
    });
    return false;
}

function showAddToCalendarForm(id) {

    $(document).ready(function () {

        var url = "/courses/getcourseschedules";
        var ajaxData = { "id": id };

        //get share course form
        $.ajax({
            type: "POST",
            //                url: "/courses/inquirecourse",
            //                data: { "courseid": id },
            url: url,
            data: ajaxData,
            success: function (data) {

                if (typeof (data) === "string") {
                    //Examples of how to assign the ColorBox event to elements
                    var ajaxDialog = $('div#ajaxDialog');

                    //check if ajax dialog exist
                    if (ajaxDialog.length == 0) {
                        var body = $('body');
                        body.append('<div id="ajaxDialog" style="display:none"></div>');
                        ajaxDialog = $('div#ajaxDialog');
                        InsertLoadingGIF(ajaxDialog);

                        //create share dialog
                        ajaxDialog.dialog({
                            autoOpen: false,
                            resizable: false,
                            draggable: false,
                            width: '500px',
                            height: 'auto',
                            title: 'Inquire'
                        });
                        //open share dialog
                        ajaxDialog.dialog('open');

                        //insert share form to div
                        ajaxDialog.html(data);

                        //close and open dialog to reposition dialog
                        ajaxDialog.dialog('close');
                        ajaxDialog.dialog('open');

                        //add close event handler
                        ajaxDialog.dialog('option', 'close',
                        function (event, ui) {
                            $(this).dialog('destroy');
                            $(this).remove();
                        });

                        //add click event handler for close button
                        var close = $('input#closeButton');
                        close.click(function () {
                            ajaxDialog.dialog('close');
                            ajaxDialog.dialog('destroy');
                            ajaxDialog.remove();
                        });

                    }
                    else {
                        ajaxDialog.dialog('open');
                    }


                }
                else {
                    if (data.Succeed == true) {
                        createErrorDialog("Add to Calendar", "This course was added to your calendar.");
                    }
                    else {
                        createErrorDialog(data.Title, data.Message);
                    }
                }
            }
        });


    });
    return false;
}

function InitAddCourseToCalendarForm(id) {
    var options = {
        dataType: 'json',
        success: showResponseDialog,  // post-submit callback 
        beforeSubmit: validateAjaxForm,
        data: { "id": id }
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 

        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    };

    $('#ajax_form').ajaxForm(options);
}

function InitInquiryForm(id, inquiryType) {
    var options = {
        dataType: 'json',
        success: showResponseDialog,  // post-submit callback 
        beforeSubmit: validateAjaxForm,
        data: { "id": id, "inquiryType": inquiryType }
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 

        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    };

    $('#ajax_form').ajaxForm(options);
}

function InitCourseDetails() {
    $(document).ready(function () {
        var courseDesc = $("#tab_course_desc");
        var courseOutline = $("#tab_course_outline");
        var adminDetails = $("#tab_admin_details");

        var divCourseDesc = $("#div_course_desc");
        var divCourseOutline = $("#div_course_outline");
        var divAdminDetails = $("#div_admin_details");

        courseDesc.click(function () {
            courseDesc.addClass("sc_tab_selected");
            courseOutline.removeClass("sc_tab_selected");
            adminDetails.removeClass("sc_tab_selected");
            divCourseDesc.show();
            divCourseOutline.hide();
            divAdminDetails.hide();
        });

        courseOutline.click(function () {
            courseDesc.removeClass("sc_tab_selected");
            courseOutline.addClass("sc_tab_selected");
            adminDetails.removeClass("sc_tab_selected");
            divCourseDesc.hide();
            divCourseOutline.show();
            divAdminDetails.hide();
        });

        adminDetails.click(function () {
            courseDesc.removeClass("sc_tab_selected");
            courseOutline.removeClass("sc_tab_selected");
            adminDetails.addClass("sc_tab_selected");
            divCourseDesc.hide();
            divCourseOutline.hide();
            divAdminDetails.show();
        });
    });


}

function InitLearnerRegistration() {
    var options = {
        dataType: 'json',
        success: showRegisterResponse,  // post-submit callback 
        beforeSubmit: validateAjaxRegistrationForm,
        error: registrationFailed
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 

        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    };

    $('#ajax_form').ajaxForm(options);
}

function validateAjaxRegistrationForm(formData, jqForm, options) {
    // formData is an array of objects representing the name and value of each field 
    // that will be sent to the server;  it takes the following form: 
    // 
    // [ 
    //     { name:  username, value: valueOfUsernameInput }, 
    //     { name:  password, value: valueOfPasswordInput } 
    // ] 
    // 
    // To validate, we can examine the contents of this array to see if the 
    // username and password fields have values.  If either value evaluates 
    // to false then we return false from this method.

    var submit = $('.form_buttons input[type="submit"], .ajax_form button[type="submit"]');

    submit.attr('disabled', 'disabled');
    submit.toggleClass('form_disabled');

    $("span.regform_loader").show();
    //insert validation logic here


    //    for (var i = 0; i < formData.length; i++) {
    //        if (!formData[i].value) {
    //            alert('Please enter a value for both Username and Password');
    //            return false;
    //        }
    //    }
    //    alert('Both fields contain values.');

}

function showRegisterResponse(data) {
    window.location.replace("/learners/registrationsuccessful");
}

function registrationFailed(result, textStatus, errorThrown) {
    var error = $("div.regform_error_div");
    error.html(result.responseText);
    error.show();

    var submit = $('.form_buttons input[type="image"], .ajax_form button[type="image"], .form_buttons input[type="submit"], .ajax_form button[type="submit"]');

    submit.removeAttr('disabled');
    submit.toggleClass('form_disabled');

    $("span.regform_loader").hide();
    xcaptchaChangeCaptchaImage();
}

function ret() {
    return temp.replace(/\{([\d]+)\}/g, function (s1, s2) { var s = dataarry[s2]; if (typeof (s) != "undefined") { if (s instanceof (Date)) { return s.getTimezoneOffset() } else { return encodeURIComponent(s) } } else { return "" } });
}

function shareCoursePageToFacebook() {    
    jQuery.ajax({
        type: "GET",
        cache: true,
        url: 'http://connect.facebook.net/en_US/all.js',
        success: function () {
            var courseTitle = $('.c_d_course_title_div h1').text();
            var address = $('.course-venue-address').text();
            var courseDates = $('.course-date-list').text();
            var courseURL = window.location.href;

            FB.init({ appId: '179142172154880', status: true, cookie: true,
                xfbml: true
            });

            FB.ui(
			   {
			       method: 'feed',
			       name: courseTitle,
			       link: courseURL,
			       caption: 'Schedules: ' + courseDates,
			       description: 'Address: ' + address
			   },
			   function (response) {
			       if (response && response.post_id) {
			           //alert('Post was published.');
			       } else {
			           //alert('Post was not published.');
			       }
			   }
			 );
        },
        dataType: 'script'
    });
    return false;
}

function shareCourseToFacebook(evt) {
    jQuery.ajax({
        type: "GET",
        cache: true,
        url: 'http://connect.facebook.net/en_US/all.js',
        success: function () {
            var parent = $(evt).parents('.c_sr_course_info');

            var title = parent.find('.c_sr_course_title h1 a');

            var courseTitle = title.text();
            var courseURL = window.location.protocol + "//" + window.location.hostname + "/" + title.attr('href');

            var address = parent.find('.c_sr_more_details_ul li:eq(1)').text();
            var courseDates = parent.find('.c_sr_status_dates').text();

            FB.init({ appId: '179142172154880', status: true, cookie: true,
                xfbml: true
            });

            FB.ui(
			   {
			       method: 'feed',
			       name: courseTitle,
			       link: courseURL,
			       caption: 'Schedules: ' + courseDates,
			       description: 'Address: ' + address
			   },
			   function (response) {
			       if (response && response.post_id) {
			           //alert('Post was published.');
			       } else {
			           //alert('Post was not published.');
			       }
			   }
			 );
        },
        dataType: 'script'
    });

    return false;
}

function shareCourseToTwitter(evt) {
    var parent = $(evt).parents('.c_sr_course_info');

    var title = parent.find('.c_sr_course_title h1 a');

    var courseTitle = title.text();
    var courseURL = window.location.protocol + "//" + window.location.hostname + "/" + title.attr('href');

    var twitterURL = "http://twitter.com/share?" + "url=" + courseURL + "&text=" + courseTitle;

    wopen(twitterURL, '', 500, 250, 'yes');
    return false;
}

function shareCoursePageToTwitter() {
    var courseTitle = $('.c_d_course_title_div h1').text();
    var courseURL = window.location.href;

    var twitterURL = "http://twitter.com/share?" + "url=" + courseURL + "&text=" + courseTitle;

    wopen(twitterURL, '', 500, 250, 'yes');
    
    return false;
}

function sharePartnerPageToFacebook() {
    jQuery.ajax({
        type: "GET",
        cache: true,
        url: 'http://connect.facebook.net/en_US/all.js',
        success: function () {
            var partnerName = $('.c_d_course_title_div h1').text();
            var profile = $('.partner-user-profile').text().substring(0, 250);

            if (profile.length > 249) {
                profile = profile + '...';
            }
            var URL = window.location.href;

            FB.init({ appId: '179142172154880', status: true, cookie: true,
                xfbml: true
            });

            FB.ui(
			   {
			       method: 'feed',
			       name: partnerName,
			       link: URL,
			       caption: '',
			       description: profile
			   },
			   function (response) {
			       if (response && response.post_id) {
			           //alert('Post was published.');
			       } else {
			           //alert('Post was not published.');
			       }
			   }
			 );
        },
        dataType: 'script'
    });
    return false;
}

function sharePartnerToFacebook(evt) {
    jQuery.ajax({
        type: "GET",
        cache: true,
        url: 'http://connect.facebook.net/en_US/all.js',
        success: function () {
            var parent = $(evt).parents('.p_details');

            var title = parent.find('.p_sr_partner_name h1 a');

            var partnerName = title.text();
            var URL = window.location.protocol + "//" + window.location.hostname + "/" + title.attr('href');

            var profile = parent.find('.p_sr_company_desc').text().substring(0, 250);

            if (profile.length > 249) {
                profile = profile + '...';
            }

            FB.init({ appId: '179142172154880', status: true, cookie: true,
                xfbml: true
            });

            FB.ui(
			   {
			       method: 'feed',
			       name: partnerName,
			       link: URL,
			       caption: '',
			       description: profile
			   },
			   function (response) {
			       if (response && response.post_id) {
			           //alert('Post was published.');
			       } else {
			           //alert('Post was not published.');
			       }
			   }
			 );
        },
        dataType: 'script'
    });

    return false;
}

function sharePartnerToTwitter(evt) {
    var parent = $(evt).parents('.p_details');

    var title = parent.find('.p_sr_partner_name h1 a');

    var partnerName = title.text();
    var URL = window.location.protocol + "//" + window.location.hostname + "/" + title.attr('href');

    var twitterURL = "http://twitter.com/share?" + "url=" + URL + "&text=" + partnerName;

    wopen(twitterURL, '', 500, 250, 'yes');
    return false;
}

function sharePartnerPageToTwitter() {
    var partnerName = jQuery.trim($('.c_d_course_title_div h1').text());
    var URL = window.location.href;

    var twitterURL = "http://twitter.com/share?" + "url=" + URL + "&text=" + partnerName;

    wopen(twitterURL, '', 500, 250, 'yes');

    return false;
}

function wopen(url, name, w, h, scrollbar) {
    // Fudge factors for window decoration space.
    // In my tests these work well on all platforms & browsers.
    var newW = w + 100;
    var newH = h + 100;
    var left = (screen.width - newW) / 2;
    var top = (screen.height - newH) / 2;
    //    var newwindow = window.open(url, 'name', 'width='+newW+',height='+newH+',left='+left+',top='+top);
    //    newwindow.resizeTo(newW, newH);
    w += 32;
    h += 96;
    var win = window.open(url,
      name,
      'width=' + w + ', height=' + h + ', ' +
      'location=no, menubar=no, left=' + left + ',top=' + top +
      ',status=no, toolbar=no, scrollbars=' + scrollbar + ', resizable=no');
    win.resizeTo(w, h);

    win.focus();
}

