﻿function GoogleMap() {
}

GoogleMap.prototype = {
    map: null,
    homeCenter: null,
    homeZoom: 9,
    ne: 0,
    sw: 0,
    dragMarker: null,
    dragMarkerMoved: false,
    dragMarkerGeo: null,
    dragInfoWindows: null,
    isFirstPassThrough: true,
    isZoomChanged: false,
    isValidBoundsChanged: false,
    isMFSSelected: false,

    Load: function(divID, lat, lng, zoom) {
        var thisMap = this;

        thisMap.homeCenter = new google.maps.LatLng(lat, lng);
        thisMap.homeZoom = zoom;
        var myOptions = {
            zoom: thisMap.homeZoom,
            center: thisMap.homeCenter,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        thisMap.map = new google.maps.Map(document.getElementById(divID), myOptions);
        thisMap.map.scrollwheel = false;

        //  CREATE THE Home BUTTON CONTROL
        var homeControlDiv = document.createElement('DIV');
        homeControlDiv.className = 'home-control';
        var homeControl = new HomeControl(thisMap.map, homeControlDiv, thisMap.homeCenter, thisMap.homeZoom);

        //  ADD THE Home BUTTON CONTROL TO THE MAP COLLECTION
        homeControlDiv.index = 1;
        thisMap.map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);

        //  CREATE AND LOAD THE DRAG-MARKER
        thisMap.dragMarker = new google.maps.Marker({
            position: this.homeCenter,
            //map: this.map,
            title: 'Home',
            draggable: true,
            icon: '/Travel/Resources/IMG/MFS/drag-marker.png',
            zIndex: 1
        });

        //  WIRE UP THE dragend EVENT
        google.maps.event.addListener(thisMap.dragMarker, 'dragstart', function() {
            if (thisMap.dragInfoWindows) {
                thisMap.dragInfoWindows.close();
            }
        });

        google.maps.event.addListener(thisMap.dragMarker, 'dragend', function() {
            //  NOTE THAT THE MARKER HAS BEEN MOVED
            thisMap.dragMarkerMoved = true;

            var position = thisMap.dragMarker.getPosition();
            MFSMarker_DragEnd(position.lat(), position.lng());
        });


        //  WIRE UP THE dragend EVENT
        //google.maps.event.addListener(googleMap.map, 'dragend', function() {
        //    if (!thisMap.dragMarkerMoved) {
        //        var bounds = googleMap.map.getBounds();
        //    }
        //});

        //  WIRE UP THE bounds_changed EVENT
        //google.maps.event.addListener(googleMap.map, 'bounds_changed', function() {
        //    if (!thisMap.dragMarkerMoved) {
        //        //thisMap.isFirstPassThrough = false;
        //        var bounds = googleMap.map.getBounds();

        //        if (thisMap.isMFSSelected) {
        //            thisMap.SetNewBounds(bounds.getNorthEast(), bounds.getSouthWest());
        //        }

        //        if (!thisMap.isFirstPassThrough) {
        //            if (thisMap.isZoomChanged) {
        //                GoogleMap_BoundsChanged(bounds.getNorthEast().lat(), bounds.getSouthWest().lat(),
        //                                       bounds.getSouthWest().lng(), bounds.getNorthEast().lng())
        //       }
        //     }
        //   }
        // });


        //  WIRE UP THE dragend EVENT
        google.maps.event.addListener(googleMap.map, 'idle', function() {
            if (!thisMap.dragMarkerMoved && thisMap.isValidBoundsChanged) {
                var bounds = googleMap.map.getBounds();

                if (thisMap.isMFSSelected) {
                    thisMap.SetNewBounds(bounds.getNorthEast(), bounds.getSouthWest());
                }
                //if (!thisMap.isFirstPassThrough) {
                    if (thisMap.isZoomChanged) {
                        GoogleMap_BoundsChanged(bounds.getNorthEast().lat(), bounds.getSouthWest().lat(),
                                                bounds.getSouthWest().lng(), bounds.getNorthEast().lng())
                    }
                //}

                thisMap.isValidBoundsChanged = false;
            }
        });

        //  WIRE UP THE zoom_changed EVENT
        google.maps.event.addListener(googleMap.map, 'dragend', function() {
            if (thisMap.isZoomChanged) {
                //  THE zoom_changed EVENT FIRES BEFORE THE MAP BOUNDS CHANGE
                //  FLAG A ValidBoundChanged
                thisMap.isValidBoundsChanged = true;
            }
        });

        //  WIRE UP THE zoom_changed EVENT
        google.maps.event.addListener(googleMap.map, 'zoom_changed', function() {
            //if (!thisMap.dragMarkerMoved) {
            //  THE zoom_changed EVENT FIRES BEFORE THE MAP BOUNDS CHANGE
            //  FLAG A ValidBoundChanged
            thisMap.isZoomChanged = true;
            //thisMap.isFirstPassThrough = false;
            thisMap.isValidBoundsChanged = true;
            //}
        });
    },

    SetNewBounds: function(ne, sw) {
        this.ne = ne;
        this.sw = sw;

        if (!this.dragMarkerMoved) {
            var newLat = this.ne.lat() + ((this.sw.lat() - this.ne.lat()) * 0.28);
            var newLng = this.sw.lng() + ((this.ne.lng() - this.sw.lng()) * 0.95);
            this.dragMarker.setPosition(new google.maps.LatLng(newLat, newLng))
        }
    },

    AddMFSSelected: function() {
        this.isMFSSelected = true;
        var bounds = googleMap.map.getBounds();

        this.dragMarker.setMap(this.map);
        this.SetNewBounds(bounds.getNorthEast(), bounds.getSouthWest());

        document.getElementById('mfs-f-w').className = 'hide';
        document.getElementById('mfs-frm-w').className = 'show';
        document.getElementById('hint').className = 'show';

        //  THIS SEEMS TO FIX A STRANGE BUG THAT CAUSES THE mfs-frm-w DIV
        //  NOT TO DISPLAY CORRECTLY FIRST TIME THROUGH.
        setTimeout(function() {
            document.getElementById('mfs-f-w').className = 'hide';
            document.getElementById('mfs-frm-w').className = 'show';
        }, 200);

    }
}

function HomeControl(map, controlDiv, home, zoom) {

    // We set up a variable for the 'this' keyword
    // since we're adding event listeners later
    // and 'this' will be out of scope.
    var control = this;

    // Set the home property upon construction
    control.SetHome(home);
    control.SetZoom(zoom);
    
    // Set CSS for the control interior
    var goHomeText = document.createElement('DIV');
    goHomeText.innerHTML = 'Home';
    controlDiv.appendChild(goHomeText);

    // Setup the click event listener for Home:
    // simply set the map to the control's current home property.
    google.maps.event.addDomListener(goHomeText, 'click', function() {

        //  CLEAR THE MAP
        SearchClear_Click();
        map.setCenter(control.GetHome());
        map.setZoom(control.GetZoom());

        //  RESET THE dragMarker
        googleMap.dragMarkerMoved = false;
        googleMap.isZoomChanged = false;
        googleMap.isValidBoundsChanged = false;
        googleMap.isMFSSelected = false;
        googleMap.dragMarker.setMap(null);

        document.getElementById('mfs-f-w').className = 'mfs-f-w';
        document.getElementById('mfs-frm-w').className = 'hide';
        document.getElementById('hint').className = 'hide';

        //  GET THE INITIAL 20 ITEMS AGAIN
        var proxy = new Web.Service.MFS();
        proxy.GetLanding20(Search_Success, Search_Fail, null);
    });
}

HomeControl.prototype = {
    home_: null,
    zoom_: null,

    GetHome: function() {
        return this.home_;
    },
    SetHome: function(home) {
        this.home_ = home;
    },
    GetZoom: function() {
        return this.zoom_;
    },
    SetZoom: function(zoom) {
        this.zoom_ = zoom;
    }
}



//  ****************************************  //
//  **                                    **  //
//  **  MFS Item                          **  //
//  **                                    **  //
//  ****************************************  //


/*
    INFO
    Length Of A Degree Of Latitude In Meters = 110810.91398242529
    Length Of A Degree Of Longitude In Meters = 98840.51152949806
    500m in Degree Of Latitude = 0.0045121909208266294680879626458013
    500m in Degree Of Longitude = 0.0050586545158740857545185332834712
*/
var openInfoWindow = null;     //  STORES THE CURRENTLY OPEN Info Window
var arrItems = new Array();    //  ARRAY FOR MFS Item SEARCH RESULTS
var lat500m = 0.0045121909208266294680879626458013;
var lng500m = 0.0050586545158740857545185332834712;
var lat250m = lat500m / 2.0;
var lng250m = lng500m / 2.0;
var locationSearch = false;
var MFSSelected = false;
var MFSSelectedAccountID = 0;
var MFSSelectedMFSItemID = 0;
var MFSSelectedLat = 0;
var MFSSelectedLng = 0;

var numPreviewCells = 0;
var previewTable = null;
var previewRow = null;


function MFSItem(map) {
    var me = this;
    me.map = map;
    me.googleMarker = null;
    me.googleInfoWindow = null;
    me.MFSItemID = null;
    me.accountID = null;
    me.title = null;
    me.lat = null;
    me.lng = null;
    me.markHTML = null;

    me.Initialise = function(item, index) {
        me.title = item.Title;
        me.MFSItemID = item.MFSItemID;
        me.accountID = item.AccountID;
        me.title = item.Title;
        me.lat = item.Lat;
        me.lng = item.Lng;

        if (item.ThumbUrl) {
            me.markHTML = '<div class="marker-window">' +
                                '<div style="float:left;">' +
                                    '<img id="img-preview" width="100px" height="75px" src="' + item.ThumbUrl.replace('~', '') + '" alt="preview" />' +
                                '</div>';
        } else {
            me.markHTML = '<div class="marker-window">' +
                                '<div style="float:left;">' +
                                    '<img id="img-preview" width="100px" height="75px" src="/Travel/Resources/IMG/MFS/default-thumb.gif" alt="preview" />' +
                                '</div>';
        }

        if (item.ContactDetails) {
            me.markHTML = me.markHTML +
                                '<div style="float:left;width:204px;overflow:hidden">' +
                                    '<h1>' + item.Title + '</h1>' +
                                    '<div style="font-size:80%;margin-left:8px;font-weight:bold;">' +
                                        item.ContactDetails +
                                    '</div>' +
                                '</div>';
        } else {
            me.markHTML = me.markHTML +
                                '<div style="float:left;width:204px;">' +
                                    '<h1 style="margin-bottom:2px;">' + item.Title + '</h1>' +
                                '</div>';
        }

        me.markHTML = me.markHTML +
                                '<div style="clear:both"></div>' +
                                '<div style="width:300px;overflow:hidden; padding-top: 8px;">' +
                                    '<p id="p-body-preview">' + item.Comment + '</p>' +
                                '</div>';

        if (item.DisplayName && item.DisplayName != '') {
            me.markHTML = me.markHTML +
                                '<div style="width:300px;overflow:hidden; padding-top: 8px;">' +
                                    '<p id="p-body-posted" style="font-size:80%;font-style:italic">Post by: ' + item.DisplayName + '</p>' +
                                '</div>';
        }

        me.markHTML = me.markHTML +
                                '<div style="width:300px;height:18px;padding: 8px 0px 0px 4px;">' +
                                '<div style="float:left;">' +
                                    '<img src="/Travel/Resources/IMG/MFS/image-icon.png">' +
                                '</div>' +
                                '<div style="float:left;margin:0px 0px 4px 2px;">' +
                                    item.NumberOfImages +
                                '</div>' +
                                '<div style="float:left;margin-left:6px;">' +
                                    '<img src="/Travel/Resources/IMG/MFS/video-icon.png">' +
                                '</div>' +
                                '<div style="float:left;margin:0px 0px 4px 2px;">' +
                                    item.NumberOfVideos +
                                '</div>' +
                                '<div style="float:left;margin-left:6px;">' +
                                    '<img src="/Travel/Resources/IMG/MFS/comment-icon.png">' +
                                '</div>' +
                                '<div style="float:left;margin:0px 0px 4px 2px;">' +
                                    item.NumberOfComments +
                                '</div>';

        if (item.NumberOfComments > 0) {
            me.markHTML = me.markHTML + '<div style="float:left;margin-left: 60px">' +
                                            '<a href="MFSView.aspx?id=' + item.MFSItemID + '"><img src="/Travel/Resources/IMG/MFS/more-btn.png" border="0"></a>' +
                                         '</div>';
        } else if (item.AccountID > 0) {
            me.markHTML = me.markHTML + '<div style="float:left;;margin-left: 60px">' +
                                            '<a href="/Travel/Products/ProductView.aspx?id=' + item.AccountID + '"><img src="/Travel/Resources/IMG/MFS/more-btn.png" border="0"></a>' +
                                         '</div>';
        }
        me.markHTML = me.markHTML + '<div style="clear:both"></div>' +
                                '</div>' +
                                '<div style="width:300px;padding-top:8px;text-align:center">' +
                                    '<div style="color:#0092cf;font-size:11px;font-weight:bold;" class="clickable" onclick="MyFavouriteSpot_Click(' + index + ')">+ Add as My Favourite Spot</div>' +
                                '</div>' +
                            '</div>';
    }

    me.SetMarker = function() {
        if (me.lat && me.lng && me.title) {
            me.googleMarker = new google.maps.Marker({
                position: new google.maps.LatLng(me.lat, me.lng),
                title: me.title,
                draggable: false,
                icon: '/Travel/Resources/IMG/MFS/item-marker.png',
                shadow: '/Travel/Resources/IMG/MFS/item-marker-shadow.png'
            });
        }

        me.googleInfoWindow = new google.maps.InfoWindow();
        me.googleInfoWindow.setContent(me.markHTML);

        //  WIRE UP THE dragend EVENT
        google.maps.event.addListener(me.googleMarker, 'click', function() {
            if (openInfoWindow) {
                openInfoWindow.CloseInfoWindow();
            }
            if (arrItems) {
                me.ShowInfoWindow();
                openInfoWindow = me;
            }
        });
    }

    me.ShowMarker = function() {
        if (me.googleMarker) {
            me.googleMarker.setMap(me.map);
        }
    }

    me.RemoveMarker = function() {
        if (me.googleMarker) {
            me.googleMarker.setMap(null);
        }
    }

    me.ShowInfoWindow = function() {
        if (me.googleMarker) {
            me.googleInfoWindow.open(me.map, me.googleMarker);
        }
    }

    me.CloseInfoWindow = function() {
        if (me.googleMarker) {
            me.googleInfoWindow.close();
        }
    }
}

MFSItem.prototype.map = null;


function SearchClear_Click() {
    if (openInfoWindow) {
        openInfoWindow.CloseInfoWindow();
    }

    while (arrItems.length > 0) {
        arrItems[0].RemoveMarker();
        arrItems.shift();
    }
    document.getElementById('sch-res-w').className = 'hide';
    document.getElementById('search-loading').className = 'hide';
}

function ShowOnMap_Click(index) {
    if (openInfoWindow) {
        openInfoWindow.CloseInfoWindow();
    }
    if (arrItems) {
        arrItems[index].ShowInfoWindow();
        openInfoWindow = arrItems[index];
        googleMap.map.setCenter(new google.maps.LatLng(arrItems[index].lat, arrItems[index].lng));

    }
}

function MyFavouriteSpot_Click(index) {
    if (openInfoWindow) {
        openInfoWindow.CloseInfoWindow();
    }
    document.location.href = '#additem';

    //  STORE THE SELECTED INFORMATION
    MFSSelected = true;
    MFSSelectedAccountID = arrItems[index].accountID;
    MFSSelectedMFSItemID = arrItems[index].MFSItemID;

    document.getElementById(txtLocation).value = arrItems[index].title;
    document.getElementById('h1-title-preview').innerHTML = arrItems[index].title;

    if (!googleMap.isMFSSelected) {
        googleMap.AddMFSSelected();
    }
}

var from = '';
function MFSMarker_DragEnd(lat, lng) {
    locationSearch = true;
    showResultsPane = true;
    from = 'MFSMarker_DragEnd';
    
    if (lat && lng) {
        var proxy = new Web.Service.MFS();
        proxy.SearchLocation(lat + lat250m, lat - lat250m, lng - lng250m, lng + lng250m, true, 10, 0, Search_Success, Search_Fail, null);
    }
}

function GoogleMap_BoundsChanged(neLat, swLat, neLng, swLng) {
    locationSearch = false;
    showResultsPane = false;
    from = 'GoogleMap_BoundsChanged';

    if (neLat && swLat) {
        var proxy = new Web.Service.MFS();
        proxy.SearchLocation(neLat, swLat, neLng, swLng, false, 20, 0, Search_Success, Search_Fail, null);
    }
}

function Search_Clicked(txt) {
    locationSearch = false;
    showResultsPane = true;
    from = 'Search_Clicked';

    document.getElementById('search-loading').className = '';
    document.getElementById('sch-res-w').className = 'hide';

    if (txt != '') {
        var proxy = new Web.Service.MFS();
        proxy.SearchText(txt, 10, 0, Search_Success, Search_Fail, null);
    }
}

function txtLocation_Changed() {
    MFSSelected = false;
    alert('changed')
}

function txtLocation_KeyUp(txt, e) {
    locationSearch = false;
    showResultsPane = false;
    from = 'txtLocation_KeyUp';

    if (e.keyCode != 9) {
        if (txt != '' && txt.length > 4) {
            var proxy = new Web.Service.MFS();
            proxy.AutoComplete(txt, 8, AutoComplete_Success, AutoComplete_Fail, null);
        }
        document.getElementById('h1-title-preview').innerHTML = txt;
    }
}

function txtWhy_KeyUp(txt) {
    if (event.keyCode != 9) {
        document.getElementById('p-body-preview').innerHTML = txt.replace(/\n/gi, '<br />');
    }
}

function txtWhy_Blur(txt) {
    document.getElementById('p-body-preview').innerHTML = txt.replace(/\n/gi, '<br />');
}

function Search_Success(result) {
    //  CLEAR THE MAP MARKERS
    if (openInfoWindow) {
        openInfoWindow.CloseInfoWindow();
    }
    while (arrItems.length > 0) {
        arrItems[0].RemoveMarker();
        arrItems.shift();
    }

    //  CLEAR THE SEARCH RESULTS
    document.getElementById('sch-res').innerHTML = '';

    var resultWrapper = document.createElement('div');
    if (acIndex >= 0) {
        //  AUTOCOMPLETE ITEM HAS BEEN SELECTED - DISPLAY IT
        var test = new MFSItem(googleMap.map);

        test.Initialise(acresult[acIndex], acIndex);
        test.SetMarker();
        test.ShowMarker();
        test.ShowInfoWindow();
        openInfoWindow = test;

        arrItems[0] = test;
        acIndex = -1;
    } else if (result.length > 0) {
        //  THIS IS A NORMAL SEARCH RESULT
        for (var i = 0; i < result.length; i++) {
            var test = new MFSItem(googleMap.map);

            test.Initialise(result[i], i);
            test.SetMarker();
            test.ShowMarker();

            arrItems[i] = test;
        }

        if (showResultsPane) {
            for (var i = 0; i < arrItems.length; i++) {
                var resultItem = document.createElement('div');
                var resultOptions = document.createElement('div');

                resultItem.setAttribute('class', 'item');
                resultItem.innerHTML = arrItems[i].title;

                resultOptions.setAttribute('class', 'options');
                var url = document.createElement('a');
                url.setAttribute('href', 'javascript:ShowOnMap_Click(' + i + ');');
                url.innerHTML = 'Show on Map';
                resultOptions.appendChild(url);
                resultOptions.innerHTML = resultOptions.innerHTML + ' | ';

                url = document.createElement('a');
                url.setAttribute('href', 'javascript:MyFavouriteSpot_Click(' + i + ');');
                url.innerHTML = 'My Favourite Spot';
                resultOptions.appendChild(url);

                resultWrapper.appendChild(resultItem);
                resultWrapper.appendChild(resultOptions);
            }
        }
    } else if (showResultsPane) {
        resultWrapper.innerHTML = locationSearch ? 'Nothing near' : 'Nothing Found';
    }

    if (showResultsPane) {
        document.getElementById('sch-res-title').innerHTML = 
            locationSearch ? 'Did You Mean?' : 'Search Results';

        document.getElementById('sch-res').innerHTML = '';
        document.getElementById('sch-res').appendChild(resultWrapper);
        document.getElementById('sch-res-w').className = '';
        document.getElementById('search-loading').className = 'hide;';
    }
    showResultsPane = false;
}

function Search_Fail(result) {
    //alert('f');
}

function Search_KeyUp(txt) {
    if (event.keyCode == 13) {
        Search_Clicked(txt);
    }
}

var acresult = null;
var acIndex = -1;
function AutoComplete_Success(result) {
    acresult = result;

    document.getElementById('did-you-mean').innerHTML = '';
    document.getElementById('did-you-mean').className = 'hide';

    if (result.length > 0) {
        var resultWrapper = document.createElement('div');

        for (var i = 0; i < result.length; i++) {
            var resultItem = document.createElement('div');

            resultItem.setAttribute('class', 'item');
            resultItem.innerHTML = result[i].Title;

            resultItem.setAttribute('onclick', 'AutoComplete_Click("' + result[i].Title + '", ' +
                        result[i].MFSItemID + ', ' + result[i].AccountID + ', ' + i + ');');

            resultWrapper.appendChild(resultItem);
        }
        
        document.getElementById('did-you-mean').appendChild(resultWrapper)
        document.getElementById('did-you-mean').className = '';
    }
}

function AutoComplete_Fail() {
}

function AutoComplete_Click(title, MFSItemId, accountID, index) {
    acIndex = index;
    
    document.getElementById(txtLocation).value = acresult[index].Title;
    document.getElementById('h1-title-preview').innerHTML = acresult[index].Title;

    //  STORE THE SELECTED INFORMATION
    MFSSelected = true;
    MFSSelectedMFSItemID = acresult[index].MFSItemID;
    MFSSelectedAccountID = acresult[index].AccountID;
    
    document.getElementById('did-you-mean').innerHTML = '';
    document.getElementById('did-you-mean').className = 'hide';

    Search_Success(null);
}

function AutoComplete_Blur() {
    document.getElementById('did-you-mean').innerHTML = '';
    document.getElementById('did-you-mean').className = 'hide';
}

function Save_Click() {
    if (!MFSSelected & !googleMap.dragMarkerMoved) {
        alert('Please drag the marker to your favourite spot on the map.');
        return;
    }

    function MSFSubmission() {
        this.Comment = document.getElementById(txtWhy).value;
        this.SubmissionEmail = document.getElementById(txtEmail).value;
        this.SubmissionDiplayName = document.getElementById(txtName).value;
    }
    function MFSItem() {
        if (MFSSelected) {
            this.MFSItemID = MFSSelectedMFSItemID;
            this.AccountID = MFSSelectedAccountID;
            this.Lat = 0;
            this.Lng = 0;
        } else {
            var position = googleMap.dragMarker.getPosition();

            this.MFSItemID = 0;
            this.AccountID = 0;
            this.Lat = position.lat();
            this.Lng = position.lng();
        }
        this.Title = document.getElementById(txtLocation).value;
    }

    var submission = new MSFSubmission();
    var item = new MFSItem();

    var proxy = new Web.Service.MFS();
    proxy.Save(submission, item, arrImage, arrVideo, Save_Success, Save_Fail, null);
}

function Save_Success(result) {
    $find('popupThanks').show();
}

function Save_Fail() {
    alert('Save Failed');
}


//  IMAGE UPLOAD
var arrImage = new Array();
function ImageItem(url, id) {
    this.ImageUrl = url;
    this.ImageID = id;
}

function HideImageMessage() {
    document.getElementById('upload-image-message').className = 'hide';
}

function PhotoUploadFail(error) {
    alert(error);
}

function PreviewImage(imageURL, imageID) {
    if (!PreviewImage.NextID) {
        PreviewImage.NextID = 0;
    }

    //  Store the Image Details
    arrImage[PreviewImage.NextID] = new ImageItem(imageURL, imageID);

    //  LIMIT THE NUMBER OF COLUMNS TO 6
    if (numPreviewCells >= 6) {
        previewRow = document.createElement('tr');
        previewTable.appendChild(previewRow);
        numPreviewCells = 0;
    }

    var imageCell = document.createElement('td');
    //imageCell.setAttribute('style', 'vertical-align: middle; padding: 12px 8px;');
    imageCell.setAttribute('class', 'img');
    numPreviewCells++;

    var newImage = document.createElement('img');
    newImage.setAttribute('width', '130');
    newImage.setAttribute('height', '97');
    //newImage.setAttribute('id', 'newImage' + PreviewImage.NextID);
    newImage.setAttribute('src', imageURL);

    imageCell.appendChild(newImage);
    previewRow.appendChild(imageCell);

    if (PreviewImage.NextID++ == 0) {
        document.getElementById('img-preview').src = imageURL;
    }

    document.getElementById('upload-image-message').className = '';
}


//  VIDEO UPLOAD
var arrVideo = new Array();
function VideoItem(embedCode, url) {
    this.EmbedCode = embedCode;
    this.Url = url;
}

var urlWatermark = 'Paste your YouTube Url Here...';
var embedWatermark = 'Paste your YouTube Embed Code Here...';

function EmbedCode_Focus(obj) {
    if (obj.value == embedWatermark) {
        obj.value = '';
        document.getElementById('upload-video-message').className = 'hide';
    }
}
function EmbedCode_Blur(obj) {
    if (obj.value == '') {
        obj.value = embedWatermark;
    }
}

function YouTubeUrl_Focus(obj) {
    if (obj.value == urlWatermark) {
        obj.value = '';
        document.getElementById('upload-video-message').className = 'hide';
    }
}

function YouTubeUrl_Blur(obj) {
    if (obj.value == '') {
        obj.value = urlWatermark;
    }
}


//  FUNCTION TO VALIDATE THE Url AND Embed Codes FOR THE 
//  YouTubeVideo UPLOAD
function ValidateVideoObject(txt) {
    var videoObject = document.getElementById(txtYouTubeUpload).value;
    var videoUrl = document.getElementById(txtYouTubeUrl).value;

    if (videoUrl.indexOf('http://www.youtube.com/') < 0) {
        alert('Invalid YouTube Url.\nPlease try again.')
        return false;
    }

    if (videoObject.indexOf('src="http://www.youtube.com/') < 0 || 
            videoObject.indexOf('type="application/x-shockwave-flash"') < 0) {
        alert('Invalid YouTube Embed Code.\nPlease try again.')
        return false;
    }

    PreviewVideo(videoObject, videoUrl);

    document.getElementById(txtYouTubeUpload).value = embedWatermark;
    document.getElementById(txtYouTubeUrl).value = urlWatermark;
    document.getElementById('upload-video-message').className = '';

    return true;
}

//  SET UP THE SCREEN PREVIEW FOR THE UPLOADED VIDEO
function PreviewVideo(videoObject, videoUrl) {
    if (!PreviewVideo.NextID) {
        PreviewVideo.NextID = 0;
    }

    //  Store the Image Details
    arrVideo[PreviewVideo.NextID] = new VideoItem(videoObject, videoUrl);

    //  GET THE WIDTH & HEIGHT
    var widthStartIndex = videoObject.indexOf('width') + 7;
    var width = videoObject.substring(widthStartIndex, videoObject.indexOf('"', widthStartIndex));

    var heightStartIndex = videoObject.indexOf('height') + 8;
    var height = videoObject.substring(heightStartIndex, videoObject.indexOf('"', heightStartIndex));


    if (width / 130 > height / 97) {
        var newHeight = 130 / width * height;
        videoObject = videoObject.replace(/width="[^"]*"/gi, 'width="130"');
        videoObject = videoObject.replace(/height="[^"]*"/gi, 'height="97"');
    } else {
    var newWidth = 97 / height * width;
        videoObject = videoObject.replace(/height="[^"]*"/gi, 'height="97"');
        videoObject = videoObject.replace(/width="[^"]*"/gi, 'width="' + newWidth + '"');
    }

    //  LIMIT THE NUMBER OF COLUMNS TO 8
    if (numPreviewCells >= 6) {
        previewRow = document.createElement('tr');
        previewTable.appendChild(previewRow);
        numPreviewCells = 0;
    }

    var videoCell = document.createElement('td');
    //videoCell.setAttribute('style', 'vertical-align: middle; padding: 12px 8px;');
    videoCell.setAttribute('id', 'newVideo' + PreviewVideo.NextID++);
    videoCell.setAttribute('class', 'vid');
    videoCell.innerHTML = videoObject;
    numPreviewCells++;

    previewRow.appendChild(videoCell);
}

