// bvk url
var url = 'http://www.kelleradvantage.com/genericsubmit.aspx';

//submitScuccess passed back from BVK

function submitSuccess(success) {
	if (success === true) {	
		$("#lead").html('<h4>Thank you for registering!</h4><p>You’ll be receiving a confirmation email<br/> in your inbox shortly.</p>');
		dcsMultiTrack('DCS.dcsuri','DeVry.edu: National Open House Landing Page Home Confirmation','WT.ti','DeVry.edu: National Open House Landing Page Home Confirmation');
	
	    var axel = Math.random() + "";
	    var a = axel * 10000000000000;
	    $("#spotlight").html('<IFRAME SRC="http://fls.doubleclick.net/activityi;src=2049738;type=natio773;cat=natio934;ord=1;num='+ a + '?" WIDTH=1 HEIGHT=1 FRAMEBORDER=0></IFRAME>');
	} else {
		$("#lead").html('<h4>There was an error in your submission.</h4>');
	}	
};

// get parameters from URL
function getVC() {
	if(window.location.href.search(/VC=/i) != -1){
		return(window.location.href.substr(window.location.href.search(/VC=/i) + 3, 6));
	}else{
		return '';
	}
};



$(document).ready(function() {

    var xmlData;
    var pathNames;
    var state;
    var location;
    var locationType = "both";
    var fancyboxOpened = false;

    // strings needed for HTML injections
    var s = "";
    var initIntroCopy = $('#intro').text();
    var initBodyTitle = $('#body-title').html();
    var initAgendaHTML = $('#agenda').html();
    var initDescriptionHTML = $('#description').html();
    var duTitle = "DeVry University National Open House";
    var dnyTitle = "DeVry College of New York National Open House";
    var nyAgendaHTML = "";
    var nyDescriptionHTML = "";

    // Get VC from param for hidden value in submit form
    $('#Vendor_Cd').val(getVC());

    $.ajax({
        type: "GET",
        url: "assets/locations.xml",
        dataType: "xml",
        async: false,
        success: function(xml) {
            xmlData = xml;
            //get values for NY Content Reset
            nyAgendaHTML = $(xmlData).find("state[param='newyork']").find("agenda:first").text();
            nyDescriptionHTML = $(xmlData).find("state[param='newyork']").find("description:first").text();
        }
    });

    $("a#open-fancybox").fancybox({
        'frameWidth': 800,
        'frameHeight': 700,
        'centerOnScroll': false,
        'overlayShow': true,
        'overlayOpacity': .8,
        'hideOnContentClick': false,
        'padding': 8,
        'callbackOnShow': function() { fancyboxOpened = true; },
        'callbackOnClose': function() { fancyboxOpened = false; }
    });

    function closeFancybox() {
        if (fancyboxOpened == true) {
            $.fn.fancybox.close();
        }
    };
    function openFancybox(state) {
        if (fancyboxOpened == false) {
            if (typeof state != "undefined") {
                $("a#open-fancybox").attr("href", "fancybox.html?state=" + state + "").trigger("click");
            }
            else {
                $("a#open-fancybox").attr("href", "fancybox.html").trigger("click");
            }
            dcsMultiTrack('DCS.dcsuri', 'DeVry.edu: National Open House Landing Page Overlay ', 'WT.ti', 'DeVry.edu: National Open House Landing Page Overlay');
        }
    };


    // handle jquery address changes
    $.address.change(function(event) {
        pathNames = $.address.pathNames();
        state = pathNames[0];
        location = pathNames[1];
        parseXml(state, location); // run paseXML with state and location values
    }); //end $.address.change


    function swapContent(state, location) {

        $(xmlData).find("state[param='" + state + "']").each(function() {
            var statename = $(this).find("statename").text();

            // change out data on page

            $(this).find("location[param='" + location + "']").each(function() {

                var locationname = $(this).find("name").text();
                var type = $(this).attr("type");

                locationType = type;

                $('#campus-name').html('&raquo; <a href="' + $(this).find('name').attr('href') + '" target="_blank">' + locationname + '</a>').show();
                $('#intro').html($(this).find("intro").text()).show();
                $('#address1').html($(this).find("address1").text()).show();
                $('#address2').html($(this).find("address2").text()).show();
                $('#address3').html($(this).find("address3").text()).show();
                $('#time').html($(this).find("time").text()).show();
                $('#agenda').html($(this).find("agenda").text());
                $('#change-location span').html($(this).find("cta").text());

                // Data change based on on graduate or undergraduate
                if (type === "graduate") {
                    $('#body-title').html('Discover How to Grow the Business of you at our<br/> ' + locationname + ' Open House&nbsp;Event');
                    $("#logo a").css("background-position", "-500px top").attr('href', 'http://www.keller.edu');
                    $('#statistic').hide();
                    $('#disclaimer').hide();
                    $('#stateurl').attr("href", "http://keller.edu").html("http://www.Keller.edu");
                    $('#copyright').attr("href", "http://www.keller.edu/keller_copyrights.jsp");
                    $('#description').html('This location offers graduate programs only.').show();
                    $('#calgary-note').hide();
                    $.address.title("DeVry University's Keller Graduate School of Management Open House");
                } else {
                    $('#body-title').html('Discover a Career-Focused Education at our<br/>  ' + locationname + ' Open House&nbsp;Event');
                    $("#logo a").css("background-position", "0px top").attr('href', 'http://www.devry.edu');
                    $('#stateurl').attr("href", "http://devry.edu").html("http://www.DeVry.edu");
                    $('#copyright').attr("href", "http://www.devry.edu/devry_copyrights.jsp");
                    $('#statistic').show();
                    $('#disclaimer').show();
                    $('#calgary-note').show();
                    $('#description').html('').hide();
                    $.address.title("DeVry University National Open House");
                }

                // form location
                $('#Location').val($(this).attr("code"));
                $('#Del_Meth').val('ONSITE');

                if (locationname === "Virtual") {
                    $('#highlights').html("Virtual Open House highlights include:");
                    $('#campus-name').hide();
                    $('#description').html('Choose to attend at a DeVry University or Keller Graduate School of Management location').show();
                    $('#Del_Meth').val('ONLINE');
                    var tempGradType = $('#Grad_Type').val();
                    if (tempGradType == "Bachelor's Degree" || tempGradType == "Master's Degree" || tempGradType == "Doctorate/Prof Degree") {
                        $('#Location').val("DVUC OL");
                    } else {
                        $('#Location').val("DV ONLINE");
                    }
                }

                $('#form-title').html('Register today for our ' + locationname + ' Open House');

            });



            // if New York
            if (state == 'newyork') {
                $.address.title(dnyTitle);
                $("#logo a").css("background-position", "-250px top").attr('href', "http://www.devry.edu/newyork");
                $("#sidebar-logos").css("background-position", "bottom left");
                $('#stateurl').text('http://www.DeVry.edu/NewYork').attr('href', 'http://www.DeVry.edu/NewYork');
            } else {
                //	$("#logo a").css("background-position","0px top")
                $("#sidebar-logos").css("background-position", "top left");
            }

            // if Virtual Open House
            if (state == 'no-state') {
                $('#campus-name').hide();
                $("#sidebar-cta").css("background-position", "right top");
            } else {
                $('#highlights').html("Open House highlights include:");
                $('#campus-name').show();
                $("#sidebar-cta").css("background-position", "left top");
            }

        });


    } // end swapContent fuction

    function resetContent(state) {
        $('#body-title').html(initBodyTitle);
        $('#intro').text(initIntroCopy);
        $('#campus-name').html('').hide();
        $('#address1').html('').hide();
        $('#address2').html('').hide();
        $('#address3').html('').hide();
        $('#time').html('').hide();

        if (state == 'newyork') {
            $('#agenda').html(nyAgendaHTML);
            $('#description').html(nyDescriptionHTML).show();
        } else {
            $('#agenda').html(initAgendaHTML);
            $('#description').html(initDescriptionHTML).show();
        }

        $('#change-location span').html('Select a location');
        $('#form-title').html('Please <a href="#" id="select-location">select a location</a> before&nbsp;registering.');
        //form location
        $('#Location').val('');
        $('#highlights').html("Open House highlights include:");

    } // end resetContent function




    function parseXml(state, location) {
        if (state && location) {
            swapContent(state, location); // get content for state and location
            dcsMultiTrack('DCS.dcsuri', 'DeVry.edu: National Open House Landing Page Home ' + state + ' ' + location + '', 'WT.ti', 'DeVry.edu: National Open House Landing Page Home ' + state + ' ' + location + '');
            closeFancybox(); // close out fancybox
        } else if (state && !location) {
            resetContent(state); // reset data
            dcsMultiTrack('DCS.dcsuri', 'DeVry.edu: National Open House Landing Page Home ' + state + '', 'WT.ti', 'DeVry.edu: National Open House Landing Page Home ' + state + '');
            openFancybox(state); // open fancybox with correct state selected.
        } else {
            dcsMultiTrack('DCS.dcsuri', 'DeVry.edu: National Open House Landing Page Home', 'WT.ti', 'DeVry.edu: National Open House Landing Page Home');
            openFancybox('no-state'); // no state and no location
        }
    }; // end parseXml function




    // change location keep alive
    $("a#change-location, a#select-location").live("click", function() {
        if (!state) {
            $('a#open-fancybox').attr('href', 'fancybox.html').trigger('click');
        } else {
            $('a#open-fancybox').attr('href', 'fancybox.html?state=' + state).trigger('click');
        }
        return false;
    });












    // form stuff

    // init auto tab
    // requires jquery auto-tab plugin
    $('#Postal_Code').autotab({ format: 'numeric' });
    $('#Area_Code').autotab({ target: 'Suffix_Phone', format: 'numeric' });
    $('#Suffix_Phone').autotab({ target: 'Phone_Number', previous: 'Area_Code', format: 'numeric' });
    $('#Phone_Number').autotab({ previous: 'Area_Code', format: 'numeric' });

    $('#Grad_Type').bind('change', function() {
        var tempGradType = $('#Grad_Type').val();
        var delMeth = $('#Del_Meth').val();
        if (delMeth == 'ONLINE') {
            if (tempGradType == "Bachelor's Degree" || tempGradType == "Master's Degree" || tempGradType == "Doctorate/Prof Degree") {
                $('#Location').val("DVUC OL");
            } else {
                $('#Location').val("DV ONLINE");
            }
        }
    });

    // setup faux ajax submit via added sript tag
    // submit handeler must respond with either submitSuccess(true); or submitSuccess(false);

    var scriptCounter = 1;

    function _makeRequest(req) {
        var fullUrl = req;
        var noCacheIE = '&noCacheIE=' + (new Date()).getTime();
        var headLoc = document.getElementsByTagName("head").item(0);
        var scriptId = 'scriptId' + scriptCounter++;
        // Create script object
        var scriptObj = document.createElement("script");
        scriptObj.setAttribute("type", "text/javascript");
        scriptObj.setAttribute("charset", "utf-8");
        scriptObj.setAttribute("src", fullUrl + noCacheIE);
        scriptObj.setAttribute("id", scriptId);
        // Append script object to document head
        headLoc.appendChild(scriptObj);
    };

    // init form validation
    // requires jquery validate plugin

    $("#lead-form").validate({
        // range for date
        // http://docs.jquery.com/Plugins/Validation/Methods/range#range
        invalidHandler: function(form, validator) {
            var locationSet = $('#Location').val();
            // if no location then hightlight select in red
            if (locationSet === '') {
                $('#form-title').html('Please <a href="#" id="select-location" style="color: #E6260F;">select a location</a> before registering.');
            } else {
                $('#validatemsg').html('<span style="color: #E6260F;">Please correct the highlighted fields below.</span>');
            }
        },
        submitHandler: function(form) {

            var First_Name_Val = $('#First_Name').val();
            var Last_Name_Val = $('#Last_Name').val();
            var Address1_Val = $('#Address1').val();
            var Postal_Code_Val = $('#Postal_Code').val();
            var Email_Val = $('#Email').val();
            var Area_Code_Val = $('#Area_Code').val();
            var Suffix_Phone_Val = $('#Suffix_Phone').val();
            var Phone_Number_Val = $('#Phone_Number').val();
            var Grad_Type_Val = $('#Grad_Type').val();
            var Grad_Year_Val = $('#Grad_Year').val();
            var Location_Val = $('#Location').val();
            var Vendor_Cd_Val = $('#Vendor_Cd').val();
            var Lead_Notes_Val = $('#Lead_Notes').val();
            var Del_Meth_Val = $('#Del_Meth').val();

            // if Grad_Type
            var Prog_Type_Val = '';

            if (locationType == "graduate") {
                Prog_Type_Val = 'G';
            } else {
                if (Grad_Type_Val == "Master's Degree" || Grad_Type_Val == "Doctorate/Prof Degree" || Grad_Type_Val == "Bachelor's Degree") {
                    Prog_Type_Val = 'G';
                }
                else {
                    Prog_Type_Val = 'U';
                }
            }

            // url set on line 2
            var submitUrl = url +
			'?First_Name=' + escape(First_Name_Val) +
			'&Last_Name=' + escape(Last_Name_Val) +
			'&Address1=' + escape(Address1_Val) +
			'&Postal_Code=' + Postal_Code_Val +
			'&Email=' + Email_Val +
			'&Area_Code=' + Area_Code_Val +
			'&Suffix_Phone=' + Suffix_Phone_Val +
			'&Phone_Number=' + Phone_Number_Val +
			'&Grad_Type=' + Grad_Type_Val +
			'&Prog_Type=' + Prog_Type_Val +
			'&Grad_Year=' + Grad_Year_Val +
			'&Location=' + Location_Val +
			'&Vendor_Cd=' + Vendor_Cd_Val +
			'&Lead_Notes=' + Lead_Notes_Val +
			'&Del_Meth=' + Del_Meth_Val +
			'&AutoFillWithZip=false&State=&City='; //set city and state to empty and pass autofill false

            // 		test url
            //		var submitUrl =  'http://bvktest.kelleradvantage.com/openhousesubmit.aspx?First_Name=Test&Last_Name=Test&Address1=Test&Postal_Code=Test&Email=a@b.com&Area_Code=312&Suffix_Phone=123&Phone_Number=1234&Grad_Type=Doctorate/Prof Degree&Prog_Type=u&Grad_Year=2000&Location=DV ONLINE&Vendor_Cd=166096&Lead_Notes=NationalOpenHouse' ;

            _makeRequest(submitUrl);

            return false;
        }
    });



    // open all rel="external" in new window

    $('a[rel="external"]').click(function() {
        window.open($(this).attr('href'));
        return false;
    });


});  // End JQuery



