﻿/********************************************/
/********        Dependency          ********/
/********************************************/
/*
<script src="/Scripts/tiny_mce/tiny_mce.js" type="text/javascript"></script>
<script src="/Scripts/jquery-ui-1.7.2.custom.min.js" type="text/javascript"></script>  
<script src="/Scripts/LiveQuery.js" type="text/javascript"></script>
<script src="/Scripts/jquery.timeentry.min.js" type="text/javascript"></script>    
*/


/********************************************/
/********      Dialog jQuery UI      ********/
/********************************************/

$(function() {
    
    // Dialog
    if ($('#dialog').dialog != null) {
        $('#dialog').dialog({
            autoOpen: false,
            width: 600,
            position: 'auto',
            resizable: false,
            draggable: true,
            close: function(event, ui) { populateSelect(); }

        });

        // Dialog Link
        $('.openDialog').click(function() {
            $('#dialog').dialog('open');
            $('#dialog').dialog('option', 'title', this.title);
            $('#dialog').dialog('option', 'ActionLink', this.id);
            $('#dialog').dialog('option', 'ControlId', $(this).parent('p').children('select').attr('id'));
            resetValidation();
            getResults();
            return false;
        });
    }
});

//populate select box / list box
function populateSelect() {
    var actionLink = $('#dialog').dialog('option', 'ActionLink');
    var selectId = $('#dialog').dialog('option', 'ControlId');
    var options = '';
    var selectedValue = [];
    
    $('#'+selectId +' :selected').each(function(i, selected) {
        selectedValue[i] = $(selected).val();
    });
    
    if ($("#" + selectId).children('option:first').val() == '') {
        options += '<option value="">' + $("#" + selectId).children('option:first').text() + '</option>';
    }

    $.getJSON('/' + actionLink + '/GetResultList', null, function(j) {
        for (var i = 0; i < j.length; i++) {
            var selected = ''
            for (var x = 0; x < selectedValue.length; x++) {
                if (j[i].Id == selectedValue[x]) {
                    var selected = 'selected="selected"';
                }
            }
            options += '<option value="' + j[i].Id + '" ' + selected + '>' + j[i].Title + '</option>';
        }
        $('#' + selectId).html(options);
    })
    $('#' + selectId).val(selectedValue);
}


/********************************************/
/*********  CRUID for Categories &   ********/
/*********  Call to action Dialog    ********/
/********************************************/

var _ajaxResults;

function getResults() {
    $('#dialogList').html('');
    var actionLink = $('#dialog').dialog('option', 'ActionLink')
    $.ajax({
        type: "GET",
        url: "/" + actionLink + "/GetResultList",
        dataType: "json",
        cache: false,
        contentType: "application/json; charset=utf-8",
        success: function(msg) {
            parseResults(msg);
        },
        error: function() {
            console.log('CE');
            displayError("<p>An error has occured. Please refresh the page and try again.</p>");
        }
    });
}

function createItem(id) {
    var actionLink = $('#dialog').dialog('option', 'ActionLink')
    var title = $('#' + id).val();
    if (validate(title, "Title")) {
        $.ajax({
            type: "GET",
            url: "/" + actionLink + "/Create",
            data: "title=" + escape(title),
            dataType: "json",
            cache: false,
            contentType: "application/json; charset=utf-8",
            success: function(msg) {
                $('#' + id).val('');
                parseResults(msg);
            },
            error: function() {
                console.log('CE');
                displayError("<p>An error has occured. Please refresh the page and try again.</p>");
            }
        });
    }
}


function deleteItem(id) {
    var actionLink = $('#dialog').dialog('option', 'ActionLink');
    $.ajax({
        type: "GET",
        url: "/" + actionLink + "/Delete/" + id,
        dataType: "json",
        cache: false,
        contentType: "application/json; charset=utf-8",
        success: function(msg) {
            parseResults(msg);
        },
        error: function() {
            console.log('CE');
            displayError("<p>An error has occured. Please refresh the page and try again.</p>");
        }
    });
}

function updateItem(id) {
    var actionLink = $('#dialog').dialog('option', 'ActionLink');
    var value = getInputValue(id);
    if (validate(value, "Title")) {
        $.ajax({
            type: "GET",
            url: "/" + actionLink + "/Update",
            data: "categoryId=" + id + "&title=" + escape(value),
            dataType: "json",
            cache: false,
            contentType: "application/json; charset=utf-8",
            success: function(msg) {
                parseResults(msg);
            },
            error: function() {
                console.log('CE');
                displayError("<p>An error has occured. Please refresh the page and try again.</p>");
            }
        });
    }
}

function parseResults(msg) {
    _ajaxResults = msg;
    var actionLink = $('#dialog').dialog('option', 'ActionLink');
    var result = '<ul id="dialogListUl">';
    for (var post in msg) {
        result += '<li>';
        result += ' <span id="' + msg[post].Id + '">' + msg[post].Title + '</span>';
        result += ' <a class="ui-state-default ui-corner-all" href="javascript:deleteItem(\'' + msg[post].Id + '\')">Delete</a> ';
        result += '</li>';
    }
    result += '</ul>';

    $('#dialogList').html(result);
    $('#dialogListUl li span').click(createInput);
}


/********************************************/
/*******         Validation          ********/
/********************************************/


function validate(value, fieldName) {
    var isValid = true;
    
    if (value == '' || value == null) {
        displayError('<p>Please enter new ' + fieldName + '.</p>');
        isValid = false;
    }else{
        for (var post in _ajaxResults) {
            if (value == _ajaxResults[post].Title) {
                displayError('<p>Entered ' + fieldName + ' already exists.</p>');
                isValid = false;
            }
        }
    }
    
    if(isValid) resetValidation();
    
    return isValid;
}

function displayError(error) {
    $('.validationSummary').html(error);
}

function resetValidation() {
    $('.validationSummary').html('');
}

/********************************************/
/*******        File Upload          ********/
/********************************************/

//upload success
function uploadResponse(file, serverData) {

    try {
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setComplete();
        progress.setStatus("Complete.");
        progress.toggleCancel(false);
        /*reference Admin.js*/
        showUploadResult(file, serverData, this.customSettings.upload_id);
    } catch (ex) {
        this.debug(ex);
    }
}


//add form
function showUploadResult(file, response, uploadName) {

    var title = file.name.substr(0, (escape(file.name.length) - 4));
    $('#'+uploadName+'_File').val(response);
    $('#TextCaption_' + uploadName).val(title);
    $('#uploadForm_' + uploadName + ' .updateAction').css('display', 'none');


    if (getFileExtension(response) == 'pdf') {
        var index = $('#thumbs_' + uploadName + ' a').size();
        var mediaTypeId = $('#' + uploadName + '_MediaTypeId').val();

        var newFile = '<p><a id="' + uploadName + '_' + index + '" href="javascript://" title="' + title + '" onclick="EditFile(this,\'' + response + '\', \'' + uploadName + '\')" >';
        newFile += title;
        newFile += '<input type="hidden" value="' + title + '" name="' + uploadName + '.Media[' + index + '].Title" id="' + uploadName + '_Media[' + index + ']_Title"/>';
        newFile += '<input type="hidden" name="' + uploadName + '.Media[' + index + '].Id" id="' + uploadName + '_Media[' + index + ']_Id"/>';
        newFile += '<input type="hidden" value="' + response + '" name="' + uploadName + '.Media[' + index + '].File" id="' + uploadName + '_Media[' + index + ']_File"/>';
        newFile += '<input type="hidden" value="' + response + '" name="' + uploadName + '.Media[' + index + '].Thumbnail" id="' + uploadName + '_Media[' + index + ']_Thumbnail"/>';
        newFile += '<input type="hidden" value="' + mediaTypeId + '" name="' + uploadName + '.Media[' + index + '].MediaTypeId" id="' + uploadName + '_Media[' + index + ']_MediaTypeId"/>';
        newFile += '</a></p>';
        
    } else {
        var index = $('#thumbs_' + uploadName + ' a').size();
        var mediaTypeId = $('#' + uploadName + '_MediaTypeId').val();

        var newFile = '<a id="' + uploadName + '_' + index + '" href="javascript://" title="' + title + '" onclick="EditFile(this,\'' + response + '\', \'' + uploadName + '\')" >';
        newFile += '<img src="' + $('#' + uploadName + '_ImagePath').val() + $('#' + uploadName + '_ThumbDirectory').val() + '/' + response + '" alt="' + title + '"/>';
        newFile += '<input type="hidden" value="' + title + '" name="' + uploadName + '.Media[' + index + '].Title" id="' + uploadName + '_Media[' + index + ']_Title"/>';
        newFile += '<input type="hidden" name="' + uploadName + '.Media[' + index + '].Id" id="' + uploadName + '_Media[' + index + ']_Id"/>';
        newFile += '<input type="hidden" value="' + response + '" name="' + uploadName + '.Media[' + index + '].File" id="' + uploadName + '_Media[' + index + ']_File"/>';
        newFile += '<input type="hidden" value="' + response + '" name="' + uploadName + '.Media[' + index + '].Thumbnail" id="' + uploadName + '_Media[' + index + ']_Thumbnail"/>';
        newFile += '<input type="hidden" value="' + mediaTypeId + '" name="' + uploadName + '.Media[' + index + '].MediaTypeId" id="' + uploadName + '_Media[' + index + ']_MediaTypeId"/>';
        newFile += '</a>';
    }
    $('#thumbs_' + uploadName).prepend(newFile);
}

//populate edit fields
function EditFile(srcEl, fileName, formId) {

    var title = $(srcEl).attr('title');
    $('#thumbs_' + formId + ' a').removeClass('selected');
    $(srcEl).addClass('selected');

    $('#selectedLinkId_' + formId).val($(srcEl).attr('id'));
    $('#selectedMediaId_' + formId).val($(srcEl).children('input:eq(1)').val());
    var sld = false;
    if($(srcEl).children('input:eq(5)').length>0){
    if ($(srcEl).children('input:eq(5)').val().toLowerCase() === 'true') sld = true;
        $('#ChkInSlideshow_' + formId).attr('checked', sld);
    }
    $('#TextCaption_' + formId).val(title);

    if (getFileExtension(fileName) == 'pdf')
    {
        var preview = '<a target="_blank" class="actionLink" href="' + $('#' + formId + '_ImagePath').val() + '/' + fileName + '" title="' + title + '">';
        preview += 'preview';
        preview += '</a>';
    }
    else {
        var preview = '<a target="_blank" href="' + $('#' + formId + '_ImagePath').val() + '/' + fileName + '" title="' + title + '">';
        preview += '<img src="' + $('#' + formId + '_ImagePath').val() + $('#' + formId + '_ThumbDirectory').val() + '/' + fileName + '" alt="' + title + '" />';
        preview += '</a>';
    }
    
    $('#' + formId + ' .previewImage').html(preview);
    
    $('#uploadForm_' + formId).show('fast');
    $('#' + formId + ' .updateAction').css('display', '');
}

var ext = getFileExtension('some.jpg');

//update
function updateFile(formId) {
    var id = $('#selectedLinkId_' + formId).val();
    var title = $('#TextCaption_' + formId).val();
    var slideShow = $('#ChkInSlideshow_' + formId).is(':checked');
    if (validate(title, 'Caption')) {
        $('#' + id).attr('title', title);
        $('#' + id).children('img').attr('title', title);
        $('#' + id).children('input:eq(0)').val(title);
        $('#' + id).children('input:eq(5)').val(slideShow);
        $('#thumbs_' + formId + ' a').removeClass('selected');
        $('#uploadForm_' + formId).slideToggle();
    }
}

//delete
function deleteFile(formId) {
    var linkId = $('#selectedLinkId_' + formId).val();
    var id = $('#selectedMediaId_' + formId).val();
    //is new event
    if (id != '') {
        $.ajax({
            type: "GET",
            url: "/ManageMedia/Delete",
            data: "mediaId=" + id,
            dataType: "text",
            cache: false,
            contentType: "application/json; charset=utf-8",
            success: function(msg) {
                $('#' + linkId).remove();
                $('#uploadForm_' + formId).slideToggle();
                rewriteIndex(formId);
            },
            error: function() {
                console.log('CE');
                //displayError("<p>An error has occured. Please refresh the page and try again.</p>");
            }
        });
    } else {
        $('#' + linkId).remove();
        $('#uploadForm_' + formId).slideToggle();
        rewriteIndex(formId);
    }
}

function rewriteIndex(formId) {
    var mediaLinks = [];
    mediaLinks = $('#thumbs_' + formId + ' a');
    for (var index = 0; index < mediaLinks.length; index++) {
        $('#thumbs_' + formId + ' a:eq(' + index + ')').attr('id', formId + '_' + index);
        $('#thumbs_' + formId + ' a:eq(' + index + ') input:eq(0)').attr('id', formId + '_Media[' + index + ']_Title');
        $('#thumbs_' + formId + ' a:eq(' + index + ') input:eq(1)').attr('id', formId + '_Media[' + index + ']_Id');
        $('#thumbs_' + formId + ' a:eq(' + index + ') input:eq(2)').attr('id', formId + '_Media[' + index + ']_File');
        $('#thumbs_' + formId + ' a:eq(' + index + ') input:eq(3)').attr('id', formId + '_Media[' + index + ']_Thumbnail');
        $('#thumbs_' + formId + ' a:eq(' + index + ') input:eq(4)').attr('id', formId + '_Media[' + index + ']_MediaTypeId');
        $('#thumbs_' + formId + ' a:eq(' + index + ') input:eq(5)').attr('id', formId + '_Media[' + index + ']_IsInSlideshow');
        $('#thumbs_' + formId + ' a:eq(' + index + ') input:eq(0)').attr('name', formId + '.Media[' + index + '].Title');
        $('#thumbs_' + formId + ' a:eq(' + index + ') input:eq(1)').attr('name', formId + '.Media[' + index + '].Id');
        $('#thumbs_' + formId + ' a:eq(' + index + ') input:eq(2)').attr('name', formId + '.Media[' + index + '].File');
        $('#thumbs_' + formId + ' a:eq(' + index + ') input:eq(3)').attr('name', formId + '.Media[' + index + '].Thumbnail');
        $('#thumbs_' + formId + ' a:eq(' + index + ') input:eq(4)').attr('name', formId + '.Media[' + index + '].MediaTypeId');
        $('#thumbs_' + formId + ' a:eq(' + index + ') input:eq(5)').attr('name', formId + '.Media[' + index + '].IsInSlideshow');
    }
}

/********************************************/
/*****         Helper functions         *****/
/********************************************/

function getInputValue(id) {
    var value = $('#' + id).text();
    if (value == '')
        var value = $('#' + id + '_input').val(); ;
    return value;
}

function createInput() {
    var srcEl = $(this);
    var value = srcEl.text();
    var resultEl = '<input type="text" id="' + this.id + '_input" class="helperTextBox" onblur="removeInput(this.id)" value="" />';
    if (value != '') {
        srcEl.html(resultEl);
        $('#' + this.id + '_input').val(value);
    }
    $('#' + this.id + '_input').focus();
}

function removeInput(id) {
    var parentId = $('#' + id).parent('span').attr('id');
    //alert(_ajaxResults[(Id = parentId)].Title);
    var srcEl = $('#' + id);
    var value = srcEl.val();
    var oldValue;
    for (var post in _ajaxResults) {
        if (parentId == _ajaxResults[post].Id) {
            oldValue = _ajaxResults[post].Title;
        }
    }
    if (value == '' || value == null) {
        srcEl.val(oldValue);
        srcEl.parent().text(oldValue);
    } else if (value != oldValue) {
        updateItem(parentId);
    }
    else {
        srcEl.parent().text(value);
    }
}

function getFileExtension(filename) {
    var extArray = filename.split('.');
    var p = extArray.length - 1;
    var extension = extArray[p];
    return extension;
}

/********************************************/
/*****            Google maps           *****/
/********************************************/

var map;
var geocoder;

function initialize() {
    if (GBrowserIsCompatible()) {   
        $('#map_canvas').css("height", "300px");
        map = new GMap2(document.getElementById("map_canvas"));
        map.setUIToDefault();
        map.clearOverlays();
    }
}

function findLocation() {
    findAddress($('#Address').val());
    $('#addressList').html('');
}

function findAddress(address) {
    geocoder = new GClientGeocoder();
    geocoder.setBaseCountryCode(".au");
    geocoder.getLocations(address, addAddressToMap);
}

function addAddressToMap(response) {
    var address = $('#Address').val();
    if (!response || response.Status.code != 200) {
        alert('Entered address "' + address + '" could not be found.');
        if ($("#addressDetails").css('display') != 'none')
            $("#addressDetails").slideToggle();
        else
            $('#addressList').slideToggle();

    } else if (response.Placemark.length > 1) {
        showResultList(response);
        if ($("#addressDetails").css('display') != 'none')
            $("#addressDetails").slideToggle();
        if ($("#addressList").css('display') == 'none')
            $('#addressList').slideToggle();
    } else if (response.Placemark[0].AddressDetails.Country == null || response.Placemark[0].AddressDetails == null) {
        alert('Entered address "' + address + '" could not be found.');
    }

    else {
        initialize();
        var place = response.Placemark[0];
        var responseLocality = '';
        var streetAddress = '';
        var postCode = '';

        var latitude = place.Point.coordinates[1];
        var longitude = place.Point.coordinates[0];
        
        if ($('#Latitude').val() !== '') latitude = $('#Latitude').val();
        if ($('#Longitude').val() !== '') longitude = $('#Longitude').val();
        
        var countryName = place.AddressDetails.Country.CountryName;
        
        if (place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName != null)
            var state = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
        else
            var state = "";
        if (place.AddressDetails.Country.AdministrativeArea.Locality != null)
            responseLocality = place.AddressDetails.Country.AdministrativeArea.Locality;
        else if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea!=null)
            responseLocality = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality;
        else
            responseLocality = place.AddressDetails.Country.AdministrativeArea;

        var locality = "";

        if (responseLocality.LocalityName != null)
            locality = responseLocality.LocalityName;
        else if (place.AddressDetails.Country.AdministrativeArea.AddressLine != null)
            locality = place.AddressDetails.Country.AdministrativeArea.AddressLine[0];
            
        if (responseLocality.PostalCode != null)
            postCode = responseLocality.PostalCode.PostalCodeNumber;

        if (responseLocality.Thoroughfare != null)
            streetAddress = responseLocality.Thoroughfare.ThoroughfareName;

        setAddressValues($('#Longitude'), longitude);
        setAddressValues($('#Latitude'), latitude);
        setAddressValues($('#StreetAddress'), streetAddress);
        setAddressValues($('#Locality'), locality);
        setAddressValues($('#Postcode'), postCode);
        setAddressValues($('#State'), state);
        setAddressValues($('#Country'), countryName);

        point = new GLatLng(latitude, longitude);
        map.setCenter(point, 16);
        if (locality!="")
            var myHtml = '<strong style="color:#000">' + $('#Title').val() + '</strong><br>' + streetAddress + '<br>' + locality + ', ' + state + ', ' + postCode + '<br>' + countryName;
        else
            var myHtml = '<strong style="color:#000">' + $('#Title').val() + '</strong><br>' + streetAddress + '<br>' + state + ', ' + postCode + '<br>' + countryName;    
        createMarker(point, myHtml);
        marker.openInfoWindowHtml(myHtml);
        if ($("#addressDetails").css('display') == 'none')
            $("#addressDetails").slideToggle();
        
    }
}

function clearLocation() {
    setAddressValues($('#Longitude'), '');
    setAddressValues($('#Latitude'), '');
    setAddressValues($('#StreetAddress'), '');
    setAddressValues($('#Locality'), '');
    setAddressValues($('#Postcode'), '');
    setAddressValues($('#State'), '');
    setAddressValues($('#Address'), '');
    setAddressValues($('#Country'), '');
    $("#addressDetails").slideToggle();
}

function setAddressValues(target, value) {
    $(target).val(value);
    $(target).parent('li').children('span').text(value);
}

function showResultList(response) {
    var html = "<ul >";
    jQuery.each(response.Placemark, function(i) {
        if (i == 0) {
            html += '<li class="resultListFirst">';
            html += 'Search Results for entered address "' + $('#Address').val() + '":';
            html += '</li>';
        } else {
            html += '<li>';
            html += i+'. <a href="javascript:findAddress(\'' + this.address + '\')">';
            html += this.address;
            html += '</a>';
            html += '</li>';
        }
    });
    html += "</ul>";
    $('#addressList').html(html);
}

function createMarker(point, myHtml) {
    var marker = new GMarker(point, { draggable: true });
    marker.openInfoWindowHtml(myHtml);
    GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml(myHtml);
    });
    GEvent.addListener(marker, "dragstart", function() {
        map.closeInfoWindow();
    });
    GEvent.addListener(marker, "dragend", function() {
        marker.openInfoWindowHtml(myHtml);
        var nLat = marker.getPoint().lat();
        var nLng = marker.getPoint().lng();

        $('#Longitude').val(nLng);
        $('#Latitude').val(nLat);
        $('#Longitude').closest('li').find('span').text(nLng);
        $('#Latitude').closest('li').find('span').text(nLat);
    });
    map.setCenter(point, 16);
    map.addOverlay(marker);
    return marker;
}

/********************************************/
/********       Features Form        ********/
/********************************************/

function hideFeatureFields(option) {
    switch (option) {
        case '1': //hyperlink text box case
            $('.eventlink').show('fast');
            $('.hyperlink').hide('fast');
            break;
        case '2': //link to event case
            $('.eventlink').hide('fast');
            $('.hyperlink').show('fast');
            break;
        default: //all fields displayed
            $('.eventlink').show('fast');
            $('.hyperlink').show('fast');
    };
}

/********************************************/
/********      TinyMCE wysiwyg      ********/
/********************************************/

tinyMCE.init({
    theme: "advanced",
    mode: "textareas",
    plugins: "paste",
    theme_advanced_toolbar_location: "top",
    theme_advanced_toolbar_align: "left",
    theme_advanced_statusbar_location: "bottom",
    theme_advanced_resizing: true,
    paste_auto_cleanup_on_paste: true,
    paste_use_dialog: false,
    //spellchecker_rpc_url : "TinyMCE.ashx?module=SpellChecker",
    //editor_selector: "mceEditor",
    paste_preprocess: function(pl, o) {
        // Content string containing the HTML from the clipboard
        var strInputCode = o.content;

        strInputCode = strInputCode.replace(/&(lt|gt);/g, function(strMatch, p1) { return (p1 == "lt") ? "<" : ">"; });

        var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");

        o.content = strTagStrippedText;
    },
    paste_postprocess: function(pl, o) {
        // Content DOM node containing the DOM structure of the clipboard
        //alert(o.node.innerHTML);
    },
    paste_convert_middot_lists: true
    //content_css : "/styles/global.css"
});

/********************************************/
/********      Slug Plugin      ********/
/********************************************/

$.fn.extend({
    slugify: function(string) {
        if (!this.is(":enabled"))
            return;

        slug = $.trim(string);

        if (slug && slug !== "") {
            var cleanReg = new RegExp("[^A-Za-z0-9-]", "g");
            var spaceReg = new RegExp("\\s+", "g");
            var dashReg = new RegExp("-+", "g");

            slug = slug.replace('&', '');
            slug = slug.replace(spaceReg, '-');
            slug = slug.replace(dashReg, "-");
            slug = slug.replace(cleanReg, "");

            if (slug.length * 2 < string.length) {
                return "";
            }

            if (slug.Length > 100) {
                slug = slug.substring(0, 100);
            }
        }

        this.val(slug.toLowerCase());
    }
});

/********************************************/
/********      Init      ********/
/********************************************/

$(document).ready(function() {

    //accordion event listing admin
    $('#accordion a.acordionLink').click(function() {
        $(this).parent('h3').parent('div').children('div').slideToggle('fast');
    });

    $('input.datepicker').live('click', function() {
        $(this).datepicker({ showOn: 'focus',
            changeMonth: true,
            changeYear: true,
            dateFormat: 'dd/mm/yy'
        }).focus();
    });

    $('input.timepicker').timeEntry();

    $('input.timepicker').live('click', function() {
        $(this).focus();
        $(this).timeEntry();
    });

    $(".deleteDate").live('click', function() {
        $(this).closest("li").remove();
        too();
    });

    $("#IsParentEvent").click(function() {
        $(".parent").slideToggle();
        $(".child").slideToggle();
        if ($(this).is(':checked')) {
            $('.childNoParent').show();
        }
        else if ($("#ParentEventID").val() == '') {
            $('.childNoParent').show();
        } else {
            $('.childNoParent').hide();
        }
    });

    if ($("#IsParentEvent").is(':checked') && $("#ParentEventID").val() == '') {
        $('.childNoParent').show();
    } else if ($("#ParentEventID").val() == '') {
        $('.childNoParent').show();
    } else {
        $('.childNoParent').hide();
    }

    $("#ParentEventID").change(function() {
        if ($(this).val() == '')
            $('.childNoParent').show();
        else
            $('.childNoParent').hide();
    });


    $("#Title").change(function() {
        $("#Slug").slugify($(this).val());
    });

    //Features form
    $("#EventId").change(function() {
        if ($(this).val() != '' && $('.hyperlink').css('display') != 'none') {
            hideFeatureFields('1');
        } else if ($(this).val() == '' && $('.hyperlink').css('display') == 'none') {
            hideFeatureFields();
        }
    });
    //Features form
    $('#Hyperlink').blur(function() {
        if ($(this).val() != '') {
            hideFeatureFields('2');
        } else if ($("#EventId").val() == '') {
            hideFeatureFields();
        }
    });
});


function too() {
    var mediaLinks = [];
    mediaLinks = $('ul#dateSelector li');
    for (var index = 0; index < mediaLinks.length; index++) {
        $('ul#dateSelector li:eq(' + index + ') '+ 'input:eq(0)').attr('id', 'Dates[' + index + ']_FromDate');
        $('ul#dateSelector li:eq(' + index + ') ' + 'input:eq(1)').attr('id', 'Dates[' + index + ']_FromTime');
        $('ul#dateSelector li:eq(' + index + ') ' + 'input:eq(2)').attr('id', 'Dates[' + index + ']_ToDate');
        $('ul#dateSelector li:eq(' + index + ') ' + 'input:eq(3)').attr('id', 'Dates[' + index + ']_ToTime');

        $('ul#dateSelector li:eq(' + index + ') ' + 'input:eq(0)').attr('name', 'Dates[' + index + '].FromDate');
        $('ul#dateSelector li:eq(' + index + ') ' + 'input:eq(1)').attr('name', 'Dates[' + index + '].FromTime');
        $('ul#dateSelector li:eq(' + index + ') ' + 'input:eq(2)').attr('name', 'Dates[' + index + '].ToDate');
        $('ul#dateSelector li:eq(' + index + ') ' + 'input:eq(3)').attr('name', 'Dates[' + index + '].ToTime');
                
    }

}



