﻿// GLOBAL VARIABLES
var _categorySelectionControl = null;
var _townSelectionControl = null;
var _gallerySettingsDiv = null;
var _gallerySelectionDiv = null;

var _uploadCount = 0;
var _isToggled = false;
var _errorLabel = null;
var _filenameIsHighlighted = false;
var finishedResizing = false;
var _cultureID = null;

// Custom Object
function baseObject(iD, typeName, cultureID, cultureShortName, textElement) {
    this.ID = iD;
    this.Name = typeName;
    this.CultureID = cultureID;
    this.CultureShortName = cultureShortName;
    this.TextElement = document.getElementById(textElement);
}

function baseProxy() {
    //properties
    this.editActive = false;
    this.infoBox = null;
    this.errorLabel = null;
    this.sessionGuid = '';
    this.galleryNameTextbox = null;
    this.galleriesDropDown = null;
    this.watermarkTextbox = null;

}

var _galleryProxy = new galleryProxy();
function galleryProxy() {



    //properties
    this.categorySelectionElement = null;
    this.townSelectionElement = null;
    this.yearSelectionElement = null;
    this.selectedYear = 0;
    this.sessionGuid = '';
    this.useCategoryAndTown = false;
    this.checkBoxPanel = null;
    this.allSelected = false;

    this.fillYearSelection = function(keepSelected) {
        if (keepSelected) {
            this.selectedYear = this.yearSelectionElement.options[this.yearSelectionElement.selectedIndex].value;
        }
        var categoryId = 0;
        if (this.categorySelectionElement.selectedIndex) {
            categoryId = this.categorySelectionElement.options[this.categorySelectionElement.selectedIndex].value;
        }
        var townId = 0;
        if (this.townSelectionElement.selectedIndex) {
            townId = this.townSelectionElement.options[this.townSelectionElement.selectedIndex].value;
        }
        MobileGallery.AjaxGalleryCallback.GetYearsBySelection(this.sessionGuid, categoryId, townId, years);
    }
}

function initMobileGallery(categorySelectionId, townSelectionId, yearSelectionId, sessionGuid, errorLabel, useCategoryAndTown, editActive, infoBox, galleryNameTextboxId, galleriesDropDown, watermarkTextbox) {

    _galleryProxy.prototype = new baseProxy();
    _galleryProxy.prototype.parent = baseProxy.prototype;
    _galleryProxy.prototype.constructor = galleryProxy();

    if (useCategoryAndTown == "True")
        _galleryProxy.useCategoryAndTown = true;
    else
        _galleryProxy.useCategoryAndTown = false;

    if (editActive == "True")
        _galleryProxy.editActive = true;
    else
        _galleryProxy.editActive = false;


    _galleryProxy.categorySelectionElement = document.getElementById(categorySelectionId);
    _galleryProxy.townSelectionElement = document.getElementById(townSelectionId);

    _galleryProxy.galleryNameTextbox = document.getElementById(galleryNameTextboxId);
    _galleryProxy.galleriesDropDown = document.getElementById(galleriesDropDown);
    _galleryProxy.yearSelectionElement = document.getElementById(yearSelectionId);
    _galleryProxy.watermarkTextbox = document.getElementById(watermarkTextbox);
    _galleryProxy.sessionGuid = sessionGuid;

    _galleryProxy.errorLabel = document.getElementById(errorLabel);
    _galleryProxy.infoBox = document.getElementById(infoBox);


    if (_galleryProxy.editActive) {
        _galleryProxy.infoBox.innerHTML = "Es wurden <b>keine</b> Bilder ausgewählt";
    }
}

// Initializes the upload Gallery
function initUploadGallery(itemsCount) {
    if (itemsCount > 0) {
        loadImages();
        createThumbnails(images, _galleryProxy.sessionGuid);
    }
    else {
        hideLoadingLayer();
    }

}

function galleries(result) {
    _galleriesDropDownElement.length = 0;
    var option = document.createElement('OPTION');
    option.text = 'Bitte wählen';
    option.value = '-1';
    _galleriesDropDownElement.options.add(option);
    for (var i = 0; i < result.length; i++) {
        option = document.createElement('OPTION');
        option.text = result[i].Name;
        option.value = result[i].GalleryID;
        _galleriesDropDownElement.options.add(option);
    }
}

function years(result) {
    _galleryProxy.yearSelectionElement.length = 0;
    var option = document.createElement('OPTION');
    option.text = "-";
    option.value = -1;
    _galleryProxy.yearSelectionElement.options.add(option);
    for (var i = 0; i < result.length; i++) {
        option = document.createElement('OPTION');
        option.text = result[i];
        option.value = result[i];
        if (_galleryProxy.selectedYear && _galleryProxy.selectedYear == option.value)
            option.selected = true;
        _galleryProxy.yearSelectionElement.options.add(option);
    }    
}


function searchArgument(iD, name, cultureID, cultureShortName, textElement) {
}


var _searchControlProxy = new searchControlProxy();
function searchControlProxy() {
    this.searchArguments = new Array();
    this.searchSettingsDiv = null;
    this.searchSelectionDiv = null;
    this.currentSessionGuid = null;
    this.checkBoxes = new Array();
    this.checkBoxesValues = new Array();
    this.uploadCheckboxValues = new Array();
    this.selectedCheckboxValues = new Array();
    this.searchOptionsDiv = null;
    this.currentlySelectedItemIndex = null;
    this.loadingLayer = null;
    this.checkBoxDiv = new Array();

    //methods
    this.addSeachArgument = function(id, name, cultureID, cultureShortName, textElement) {
        searchArgument.prototype = new baseObject(id, name, cultureID, cultureShortName, textElement);
        var t = new searchArgument(id, name, cultureID, cultureShortName, textElement);
        this.searchArguments.push(t);
    }

    this.addCheckBox = function(id, value) {
        var t = document.getElementById(id);
        this.checkBoxes.push(t);
        this.checkBoxesValues.push(value);
    }

    this.addCheckBoxDiv = function(id) {
        var t = document.getElementById(id);
        this.checkBoxDiv.push(t);
    }


    this.clearCheckBoxes = function() {
        this.checkBoxes = new Array();
    }

    this.getSearchArgumentsBySelection = function(keepSelected) {
        if (keepSelected) {
            for (c = 0; c < this.checkBoxes.length; c++) {
                if (this.checkBoxes[c] != null) {
                    if (this.checkBoxes[c].checked)
                        this.selectedCheckboxValues.push(this.checkBoxesValues[c]);
                }
            }
        }
        var categoryId = 0;
        if (_galleryProxy.categorySelectionElement.selectedIndex > 0) {
            categoryId = _galleryProxy.categorySelectionElement.options[_galleryProxy.categorySelectionElement.selectedIndex].value;
        }
        var townId = 0;
        if (_galleryProxy.townSelectionElement.selectedIndex > 0) {
            townId = _galleryProxy.townSelectionElement.options[_galleryProxy.townSelectionElement.selectedIndex].value;
        }
        var year = 0;
        if (_galleryProxy.yearSelectionElement.selectedIndex > 0) {
            year = _galleryProxy.yearSelectionElement.options[_galleryProxy.yearSelectionElement.selectedIndex].value;
        }
        if (!_galleryProxy.editActive)
            _searchControlProxy.showLoadingLayer();

        MobileGallery.AjaxGalleryCallback.GetAllSearchArgumentsBySelection(_searchControlProxy.currentSessionGuid, categoryId, townId, year, this.triggerSearchArguments);
    }

// Function that triggers the Selection on the Live Page to visualize the Checkboxes and hide them.
    this.triggerSearchArguments = function(result) {
        if (result != null) {
            for (z = 0; z < _searchControlProxy.checkBoxesValues.length; z++) {
                 _searchControlProxy.checkBoxes[z].checked = false;
                _searchControlProxy.checkBoxDiv[z].style.display = 'none';
            }
            for (count = 0; count < result.length; count++) {
                for (z = 0; z < _searchControlProxy.checkBoxesValues.length; z++) {
                    if (result[count].SearchArgumentID == _searchControlProxy.checkBoxesValues[z]) {                        
                        _searchControlProxy.checkBoxDiv[z].style.display = '';
                    }
                }
            }
            if (!_galleryProxy.editActive)
                _searchControlProxy.hideLoadingLayer();
        }
    }

    this.toggleSearchBoxes = function(searchArgumentIDs) {
        if (_selectedItems == 1) {
            for (i = 0; i < this.checkBoxes.length; i++) {
                if (searchArgumentIDs != null) {
                    var foundItem = false;
                    if (searchArgumentIDs.length > 0) {
                        for (j = 0; j < searchArgumentIDs.length; j++) {
                            if (parseInt(this.checkBoxesValues[i]) == searchArgumentIDs[j]) {
                                this.checkBoxes[i].checked = true;
                                foundItem = true;
                            }
                        }
                        if (!foundItem)
                            this.checkBoxes[i].checked = false;
                    }
                    else {
                        for (i = 0; i < this.checkBoxes.length; i++) {
                            this.checkBoxes[i].checked = false;
                        }
                    }
                } else if (_selectedItems == 0) {
                    for (i = 0; i < this.checkBoxes.length; i++) {
                        this.checkBoxes[i].checked = false;
                    }
                }

            }

        }
        else if (_selectedItems == 0) {
            for (i = 0; i < this.checkBoxes.length; i++) {
                this.checkBoxes[i].checked = false;
            }
        }

    }

    this.toggleCheckMark = function(sessionGuid, checkBoxValue, checkBox) {
        var selectedCheckbox = document.getElementById(checkBox);
        for (i = 0; i < _galleryImageIds.length; i++) {
            if (_galleryImageIds[i] != null) {
                var dummyArray = new Array();
                dummyArray = _searchArgumentIDs[i];

                var foundItem = false;
                if (selectedCheckbox.checked) {
                    for (counting = 0; counting < dummyArray.length; counting++) {
                        if (parseInt(checkBoxValue) == dummyArray[counting]) {
                            foundItem = true;
                            // Do nothing!
                        }
                    }
                    if (foundItem == false) {
                        dummyArray.push(checkBoxValue);
                    }
                }
                else {
                    for (counting = 0; counting < dummyArray.length; counting++) {
                        if (parseInt(checkBoxValue) == dummyArray[counting]) {
                            dummyArray[counting] = null;
                        }
                    }
                }


                MobileGallery.AjaxGalleryCallback.InsertSearchArgumentRelation(sessionGuid, _galleryImageIds[i], dummyArray, i, this.onSuccessToggleCheckMark, this.onFailureToggleCheckMark);
            }
        }
    }

    this.onSuccessToggleCheckMark = function(retVal) {
        if (retVal.Message == null || typeof retVal.Message == 'undefined') {
            if (retVal.Index > 0 && retVal.CheckBoxValues.Length > 0) {
                _searchArgumentIDs[retVal.Index] = retVal.CheckBoxValues;
            }
        }
        else
            this.onFailureToggleCheckMark(retVal);
    }

    this.onFailureToggleCheckMark = function(retVal) {
        alert(retVal.Message);
    }

    this.validateCheckBoxes = function() {
        this.uploadCheckboxValues = new Array();
        for (i = 0; i < this.checkBoxes.length; i++) {
            if (this.checkBoxes[i].checked)
                this.uploadCheckboxValues.push(this.checkBoxesValues[i]);
        }
    }

    this.showLoadingLayer = function() {
    _searchControlProxy.loadingLayer.style.display = '';
    }
    this.hideLoadingLayer = function() {
    _searchControlProxy.loadingLayer.style.display = 'none';
    }
}

function initSearchControl(searchSettingsDiv, searchSelectionDiv, searchOptionsDiv, currentSessionGuid) {
    _searchControlProxy.searchSettingsDiv = document.getElementById(searchSettingsDiv);
    _searchControlProxy.searchSelectionDiv = document.getElementById(searchSelectionDiv);
    _searchControlProxy.searchOptionsDiv = document.getElementById(searchOptionsDiv);
    _searchControlProxy.currentSessionGuid = currentSessionGuid;
}


function hideSearchEdit() {
    _searchControlProxy.searchSettingsDiv.style.display = 'none';
    _searchControlProxy.searchSelectionDiv.style.display = '';
    hideSendingLayer();
}

function showSearchEdit() {
    _searchControlProxy.searchSettingsDiv.style.display = '';
    _searchControlProxy.searchSelectionDiv.style.display = 'none';
}

function reloadSearchItems() {
    MobileGallery.AjaxGalleryCallback.GetAllSearchArguments(_searchControlProxy.currentSessionGuid, searchArguments);
}

function searchArguments(result) {    
        // Clear
        if (_searchControlProxy.searchOptionsDiv.hasChildNodes()) {
            while (_searchControlProxy.searchOptionsDiv.childNodes.length >= 1) {
                _searchControlProxy.searchOptionsDiv.removeChild(_searchControlProxy.searchOptionsDiv.firstChild);
            }
        }

        var label = null;
        var option = null;
        var div = null;
        _searchControlProxy.clearCheckBoxes();
        for (var i = 0; i < result.length; i++) {
            option = document.createElement('input');
            div = document.createElement('div');
            option.type = "checkbox"
            option.id = "checkbox" + i;
            for (var j = 0; j < result[i].Translations.length; j++) {
                if (result[i].Translations[j].CultureID == _cultureID) {
                    option.name = result[i].Translations[j].Name;
                    option.value = result[i].Translations[j].SearchArgumentID;
                    label = document.createElement('label');
                    label.htmlFor = "checkbox" + i;
                    label.appendChild(document.createTextNode(result[i].Translations[j].Name));
                }
            }
            if (_searchControlProxy.currentlySelectedItemIndex != null) {

                for (x = 0; x < _searchArgumentIDs[_searchControlProxy.currentlySelectedItemIndex].length; x++) {
                    if (_searchArgumentIDs[_searchControlProxy.currentlySelectedItemIndex][x] == parseInt(option.value))
                        option.checked = true;
                }
            }
            div.appendChild(option)
            div.appendChild(label);

            _searchControlProxy.searchOptionsDiv.appendChild(div);
            option.disabled = false;


            if (option.addEventListener) {
                option.addEventListener('click', function(optionValue, optionId) { return function(event) { _searchControlProxy.toggleCheckMark(_galleryProxy.sessionGuid, optionValue, optionId); } } (option.value, option.id), false);
            }
            else {
                option.attachEvent('onclick', function(optionValue, optionId) { return function(event) { _searchControlProxy.toggleCheckMark(_galleryProxy.sessionGuid, optionValue, optionId); } } (option.value, option.id));
            }
            _searchControlProxy.addCheckBox(option.id, option.value);
        }   

    if (!_galleryProxy.editActive)
        _searchControlProxy.hideLoadingLayer();
}

function InsertSearchArgument() {
    if (_searchControlProxy.searchArguments != null && _searchControlProxy.searchArguments.length > 0) {
        var searchNames = new Array();
        var searchCultureIDs = new Array();
        for (var i in _searchControlProxy.searchArguments) {
            if (_searchControlProxy.searchArguments[i].TextElement.value != "") {
                searchNames.push(_searchControlProxy.searchArguments[i].TextElement.value);
                searchCultureIDs.push(_searchControlProxy.searchArguments[i].CultureID);
            }
        }
        if (searchNames.length > 0 && searchCultureIDs.length > 0) {
            MobileGallery.AjaxGalleryCallback.AddSearchArgument(searchNames, searchCultureIDs, _searchControlProxy.currentSessionGuid, onSearchSuccess, onSearchFailure);
        }
    }
    else {
        addErrorMessage('Bitte geben Sie einen Kategorienamen ein.');
    }
}

function onSearchSuccess(args) {
    alert(args);
    if (_searchControlProxy.searchArguments != null && _searchControlProxy.searchArguments.length > 0) {
        for (searchArgument in _searchControlProxy.searchArguments) {
            if (_searchControlProxy.searchArguments.hasOwnProperty(searchArgument)) {
                searchArgument.textElement.value = '';
            }
        }
    }
}

function onSearchFailure(args) {
    _errorLabel.value = args;
}




function imageFinishedCallback() {
    finishedResizing = true;
    hideDarkLayer();
    hideLoadingLayer();
    loadImages();
}

// Sets an Image
function image(clientID, imageUrl, outerDivId, checkBoxId) {
    this.imageUrl = imageUrl;
    this.element = document.getElementById(clientID);
    this.element.src = imageUrl;
    this.outerDivId = outerDivId;
    this.checkBoxId = checkBoxId;
}

function setImageTimeout() {
    if (!finishedResizing) {
        loadImages();
        setTimeout(setImageTimeout, 3000);
    }
}

function createThumbnails(images) {
    var hasItems = false;
    if (images != null) {
        var imageArray = new Array(images.length);
        for (var i = 0; i < images.length; i++) {
            if (images[i] != null) {
                imageArray[i] = images[i].imageUrl;
                hasItems = true;
            }
        }
        if (imageArray.length > 0 && hasItems) {
            showDarkLayer();
            showLoadingLayer();
            MobileGallery.AjaxGalleryCallback.CreateThumbnail(imageArray, _galleryProxy.sessionGuid, imageFinishedCallback);
            setImageTimeout();
        }
    }
}

var _galleryId = null;
function sendFiles() {
    if (_galleryProxy.useCategoryAndTown && !_useGeoLocating) {
        if (_galleryProxy.townSelectionElement.options[_galleryProxy.townSelectionElement.selectedIndex].value > 0 && _galleryProxy.categorySelectionElement.options[_galleryProxy.categorySelectionElement.selectedIndex].value > 0) {
            _galleryProxy.errorLabel.innerHTML = '';
            createGallery();
        } else {

            if (_galleryProxy.townSelectionElement.options[_galleryProxy.townSelectionElement.selectedIndex].value <= 0 && _galleryProxy.categorySelectionElement.options[_galleryProxy.categorySelectionElement.selectedIndex].value <= 0) {
                _galleryProxy.errorLabel.innerHTML = 'Bitte wählen Sie eine Ortschaft und eine Kategorie aus.';
            }
            else {
                if (_galleryProxy.townSelectionElement.options[_galleryProxy.townSelectionElement.selectedIndex].value <= 0) {
                    _galleryProxy.errorLabel.innerHTML = 'Bitte wählen Sie eine Ortschaft aus.';
                }
                else {
                    _galleryProxy.errorLabel.innerHTML = 'Bitte wählen Sie eine Kategorie aus.';
                }
            }
        }
    }
    else if (_galleryProxy.useCategoryAndTown && _useGeoLocating) {
        if (_galleryProxy.categorySelectionElement.options[_galleryProxy.categorySelectionElement.selectedIndex].value <= 0) {
            _galleryProxy.errorLabel.innerHTML = 'Bitte wählen Sie eine Kategorie aus.';
        }
        else {
            _galleryProxy.errorLabel.innerHTML = '';
            createGallery();
        }
    }
    else if (!_galleryProxy.useCategoryAndTown && _useGeoLocating) {
        // Has to be created!
    }
    else if (!_galleryProxy.useCategoryAndTown) {
        if (_galleryProxy.galleryNameTextbox.value != "" || _galleryProxy.galleriesDropDown.options[_galleryProxy.galleriesDropDown.selectedIndex].value > 0) {
            _galleryProxy.errorLabel.innerHTML = '';
            if (!_useExistingGalleries && _galleryProxy.galleryNameTextbox.value != "")
                createGallery();
            else if (_useExistingGalleries && _galleriesDropDownElement.options[_galleriesDropDownElement.selectedIndex].value > 0) {
                _galleryId = _galleriesDropDownElement.options[_galleriesDropDownElement.selectedIndex].value;
                uploadFiles();
            }
            else
                _galleryProxy.errorLabel.innerHTML = 'Bitte geben Sie einen Galerienamen ein oder wählen sie aus den existierenden Galerien aus1!';

        } else
            _galleryProxy.errorLabel.innerHTML = 'Bitte geben Sie einen Galerienamen ein oder wählen sie aus den existierenden Galerien aus2!';
    }
    else {
        createGallery();
    }
}



function createGallery() {
    _searchControlProxy.validateCheckBoxes();
    if (_useGeoLocating) {
        showDarkLayer();
        showSendingLayer();
        _activeUploads = 0;
        for (var i = 0; i <= _fileNames.length; i++) {
            if (_fileNames[i] != null) {
                _uploadCount++;
                if (_uploadCount >= 2)
                    setTimeout("MobileGallery.AjaxGalleryCallback.CreateGalleryByLocation('" + _galleryProxy.sessionGuid + "','" + _galleryProxy.categorySelectionElement.options[_galleryProxy.categorySelectionElement.selectedIndex].value + "','" + _fileUrls[i] + "','" + i + "','" + _cultureID + "'," + onSuccessfullCreateGalleryByLocation + ");", 300 * i > 10 ? 1 : i * 2);
                else
                    setTimeout("MobileGallery.AjaxGalleryCallback.CreateGalleryByLocation('" + _galleryProxy.sessionGuid + "','" + _galleryProxy.categorySelectionElement.options[_galleryProxy.categorySelectionElement.selectedIndex].value + "','" + _fileUrls[i] + "','" + i + "','" + _cultureID + "'," + onSuccessfullCreateGalleryByLocation + ");", 1000 * i > 10 ? 1 : i * 2);

            }
        }
    }
    else if (_galleryProxy.useCategoryAndTown)
        MobileGallery.AjaxGalleryCallback.CreateGallery(_galleryProxy.sessionGuid, _galleryProxy.categorySelectionElement.options[_galleryProxy.categorySelectionElement.selectedIndex].value, _galleryProxy.townSelectionElement.options[_galleryProxy.townSelectionElement.selectedIndex].value, _cultureID, onSuccessfullCreateGallery);
    else if (!_galleryProxy.useCategoryAndTown)
        MobileGallery.AjaxGalleryCallback.CreateGalleryByGalleryName(_galleryProxy.sessionGuid, _galleryProxy.galleryNameTextbox.value, onSuccessfullCreateGallery);

}

function onSuccessfullCreateGallery(args) {
    if (args != null) {
        if (args.GalleryID > 0) {
            _galleryId = args.GalleryID;
            uploadFiles();
        }
        else
            _galleryProxy.errorLabel.innerHTML = args.ErrorMessage;
    }
}



var _googleStatus = 0;
function onSuccessfullCreateGalleryByLocation(args) {
    if (args != null) {
        if (args.Status == 1) {
            uploadFile(args.FileName, args.GalleryID, args.Count);
        }
        else if (args.Status == 3 || _googleStatus == 3) {
            _googleStatus = 3;
            _galleryProxy.errorLabel.innerHTML = "Google's Abfragelimit erreicht! Bitte versuchen Sie es in 24H nochmals.";
            hideDarkLayer();
            hideSendingLayer();
        }
        else if (args.Status == 4 || _googleStatus == 4) {
            _googleStatus = 4;
            _galleryProxy.errorLabel.innerHTML = "Google hat die Abfrage verweigert!";
            hideDarkLayer();
            hideSendingLayer();
        }
        else
            _uploadCount--;
    }
    else
        _uploadCount--;

    if (_uploadCount == 0) {
        hideDarkLayer();
        hideSendingLayer();
    }
}

function uploadFile(filename, galleryId, count) {
    if (filename != null && galleryId != null && count != null) {
        MobileGallery.AjaxGalleryCallback.UploadPicture(_fileUrls[count], _galleryProxy.sessionGuid, filename, images[count].outerDivId, images[count].checkBoxId, galleryId, _galleryProxy.watermarkTextbox.value, _searchControlProxy.uploadCheckboxValues.toString(), onUploadSuccess);

        _fileNames[count] = null;
    }
}


function uploadFiles() {
    if (_fileNames.length > 0) {
        showDarkLayer();
        showSendingLayer();
        _activeUploads = 0;
        for (var i = 0; i <= _fileNames.length; i++) {
            if (_fileNames[i] != null) {
                setTimeout("MobileGallery.AjaxGalleryCallback.UploadPicture('" + _fileUrls[i] + "','" + _galleryProxy.sessionGuid + "','" + _fileNames[i] + "','" + images[i].outerDivId + "','" + images[i].checkBoxId + "','" + _galleryId + "','" + _galleryProxy.watermarkTextbox.value + "','" + _searchControlProxy.uploadCheckboxValues.toString() + "'," + onUploadSuccess + ");", 200 * i * 2);
                //MobileGallery.AjaxGalleryCallback.UploadPicture(_fileUrls[i], _galleryProxy.sessionGuid, _fileNames[i], images[i].outerDivId, images[i].checkBoxId, _galleryId, _galleryProxy.watermarkTextbox.value, _searchControlProxy.uploadCheckboxValues, onUploadSuccess);
                //setTimeout("MobileGallery.AjaxGalleryCallback.UploadPicture('" + _fileUrls[i] + "','" + _galleryProxy.sessionGuid + "','" + _fileNames[i] + "','" + images[i].outerDivId + "','" + images[i].checkBoxId + "','" + _galleryId + "','" + _galleryProxy.watermarkTextbox.value + "'," + onUploadSuccess + ");", 200 * i * 2);
                //MobileGallery.AjaxGalleryCallback.UploadPicture(_fileUrls[i], _galleryProxy.sessionGuid, _fileNames[i], images[i].outerDivId, images[i].checkBoxId, _galleryId, _galleryProxy.watermarkTextbox.value, onUploadSuccess);

                _uploadCount++;
                _fileNames[i] = null;
            }
        }
        return true;
    }
}

// Successfull send of an image. Returns the image name as argument
function onUploadSuccess(args) {
    var finished = false;

    if (args.Uploaded) {
        document.getElementById(args.OuterDivID).className = 'iP_oDCM';
        document.getElementById(args.OuterDivID).style.opacity = '0.5';
        document.getElementById(args.CheckBoxID).checked = false;
        informationToggle(false);
    }

    // Check for last item
    _uploadCount--;
    if (_uploadCount == 0) {
        hideDarkLayer();
        hideSendingLayer();
    }
    return true;
}

var _useExistingGalleries = false;
function toggleExistingGalleries() {
    if (!_useExistingGalleries) {
        _useExistingGalleries = true;
        _galleryProxy.galleriesDropDown.disabled = false;
        MobileGallery.AjaxGalleryCallback.GetAllGalleries(_galleryProxy.sessionGuid, galleries);
    }
    else {
        _useExistingGalleries = false;
        _galleryProxy.galleriesDropDown.disabled = true;
    }
}

var _useGeoLocating = false;
function toggleGeoLocating() {
    if (!_useGeoLocating) {
        _useGeoLocating = true;
        _galleryProxy.townSelectionElement.disabled = true;
    }
    else {
        _useGeoLocating = false;
        _galleryProxy.townSelectionElement.disabled = false;
        MobileGallery.AjaxGalleryCallback.GetAllTowns(_cultureID, towns);
    }

}

var _useWatermark = false;
function toggleWatermark() {
    if (!_useWatermark) {
        _useWatermark = true;
        _galleryProxy.watermarkTextbox.disabled = false;
    }
    else {
        _useWatermark = false;
        _galleryProxy.watermarkTextbox.disabled = true;
    }

}

var _selectedItems = 0;
function informationToggle(addItem) {
    if (_galleryProxy.editActive) {
        if (addItem) {
            _selectedItems++;
        }
        else {
            _selectedItems--;
        }

        if (_selectedItems == 1) {
            _galleryProxy.infoBox.innerHTML = "Es wurde <b>" + _selectedItems + "</b> Bild ausgewählt";
            _searchControlProxy.searchSelectionDiv.style.display = '';
            //_searchControlProxy.searchSettingsDiv.style.display = '';
        }
        else if (_selectedItems > 1) {
            _searchControlProxy.searchSelectionDiv.style.display = 'none';
            _searchControlProxy.searchSettingsDiv.style.display = 'none';
            _galleryProxy.infoBox.innerHTML = "Es wurden <b>" + _selectedItems + "</b> Bilder ausgewählt";
        }
        else
            _galleryProxy.infoBox.innerHTML = "Es wurden <b>keine</b> Bilder ausgewählt";
    }

}

function toggleUseSearchArguments() {
    if (_galleryProxy.checkBoxPanel.style.display == 'none') {
        _galleryProxy.checkBoxPanel.style.display = '';
    }
    else {
        _galleryProxy.checkBoxPanel.style.display = 'none';
    }
}


// Toggle all boxes
function toggleBoxes(filename, fileUrl, checkBoxID, index, outerDivId, imageId) {
    var checkBox = document.getElementById(checkBoxID);
    if (checkBox != null) {

        if (_isToggled) {
            _fileNames[index] = filename;
            _fileUrls[index] = fileUrl;
            _outerDivs[index] = document.getElementById(outerDivId);
            _outerDivs[index].className = "iP_oDCM";
            _galleryImageIds[index] = imageId;
        }
        else {
            _fileNames[index] = null;
            _fileUrls[index] = null;
            _outerDivs[index].className = "iP_oDC";
            _outerDivs[index] = null;
            _galleryImageIds[index] = null;
        }

        _searchControlProxy.toggleSearchBoxes(null);

        if (!checkBox.checked)
            informationToggle(true);

        checkBox.checked = _isToggled;

        if (!checkBox.checked)
            informationToggle(false);
    }
}

// Toggles a single checkbox
var _selectedSearchArguments = null;
function toggleCheckBox(index, fileUrl, filename, checkBoxID, outerDivId, imageId) {
    var checkBox = document.getElementById(checkBoxID);
    if (checkBox != null) {

        if (!checkBox.disabled) {

            if (_fileNames[index] != null) {
                _fileNames[index] = null;
                _fileUrls[index] = null;
                checkBox.checked = false;
                if (_outerDivs[index] != null)
                    _outerDivs[index].className = "iP_oDC";
                _outerDivs[index] = null;
                _galleryImageIds[index] = null;
                informationToggle(false);
                _selectedSearchArguments[index] = null;
                if (_selectedItems == 1) {
                    if (_selectedSearchArguments.length > 0) {
                        for (count = 0; count < _selectedSearchArguments.length; count++) {
                            if (_selectedSearchArguments[count] != null && typeof _selectedSearchArguments[count] != undefined) {
                                _searchControlProxy.toggleSearchBoxes(_selectedSearchArguments[count]);
                                _searchControlProxy.currentlySelectedItemIndex = null;
                            }
                        }
                    }
                    else {
                        _searchControlProxy.toggleSearchBoxes(null);
                    }
                }
                else if (_selectedItems == 0) {
                    _searchControlProxy.toggleSearchBoxes(null);
                }
            }
            else {

                _fileNames[index] = filename;
                _fileUrls[index] = fileUrl;
                _outerDivs[index] = document.getElementById(outerDivId);
                _outerDivs[index].className = "iP_oDCM";
                checkBox.checked = true;
                _galleryImageIds[index] = imageId;
                informationToggle(true);

                if (_selectedSearchArguments == null) {
                    _selectedSearchArguments = new Array();
                }
                _selectedSearchArguments[index] = _searchArgumentIDs[index];

                _searchControlProxy.currentlySelectedItemIndex = index;
                _searchControlProxy.toggleSearchBoxes(_selectedSearchArguments[index]);

            }
        }

    }

}


function showDarkLayer() {

    document.getElementById('darkLayer').className = 'darkLayer';
    document.getElementById('sendingLayer').style.display = '';
}

function hideDarkLayer() {

    document.getElementById('darkLayer').className = '';
    document.getElementById('sendingLayer').style.display = 'none';
}

function showSendingLayer() {
    document.getElementById('sendingLayer').className = 'sendingLayer';
    document.getElementById('sendingLayer').style.display = '';
}

function hideSendingLayer() {
    document.getElementById('sendingLayer').className = '';
    document.getElementById('sendingLayer').style.display = 'none';
}

function showLoadingLayer() {
    document.getElementById('loadingLayer').className = 'loadingLayer';
    document.getElementById('loadingLayer').style.display = '';
}
function hideLoadingLayer() {
    document.getElementById('loadingLayer').className = '';
    document.getElementById('loadingLayer').style.display = 'none';
}


// Edit functions
function highlightFilename(filenameLabel, outerDivClientId) {
    document.getElementById(filenameLabel).className += ' highlightFilename';

}
function lowlightFilename(filenameLabel, outerDivClientId) {
    document.getElementById(filenameLabel).className = document.getElementById(filenameLabel).className.replace(' highlightFilename', '');

}

var _galleryNameElement = null;
var _galleryNameDiv = null;
var _onClickScript = null;
var _textBoxDiv = null;
var _textBox = null;
var _deleteGalleryDiv = null;
function createGalleryNameTextbox(galleryNameId, galleryNameDivId, galleryId, deleteGalleryDiv) {
    _galleryNameElement = document.getElementById(galleryNameId);
    _galleryNameDiv = document.getElementById(galleryNameDivId);
    _galleryId = galleryId;
    _deleteGalleryDiv = document.getElementById(deleteGalleryDiv);

    _onClickScript = _galleryNameDiv.getAttribute('onclick');
    _galleryNameDiv.onclick = null;


    _textBoxDiv = document.createElement('div');
    _textBoxDiv.className = 'editGalleryNameDiv';
    _textBoxDiv.title = 'Galerie Name editieren';

    _textBox = document.createElement('input');
    _textBox.type = 'text';
    _textBox.value = _galleryNameElement.innerHTML;
    _textBox.className = 'editGalleryName';

    saveImage = document.createElement('img');
    saveImage.className = 'saveImage';
    saveImage.src = '/App_Themes/Bytix/img/save.png';
    saveImage.onclick = function() { saveGalleryName(galleryId); };
    saveImage.setAttribute('alt', 'Speichern');
    saveImage.setAttribute('title', 'Speichern');

    abortImage = document.createElement('img');
    abortImage.className = 'abortEdit';
    abortImage.src = '/App_Themes/Bytix/img/delete.png';
    abortImage.onclick = function() { recreateGalleryLabel(true); };
    abortImage.setAttribute('alt', 'Abbrechen');
    abortImage.setAttribute('title', 'Abbrechen');

    _textBoxDiv.appendChild(_textBox);
    _textBoxDiv.appendChild(saveImage);
    _textBoxDiv.appendChild(abortImage);

    _galleryNameDiv.removeChild(_galleryNameElement);
    _galleryNameDiv.appendChild(_textBoxDiv);


    _deleteGalleryDiv.style.display = "none";



}

function createTextbox(filenameDivId, outerImageDivId, galleryImageId, index, checkboxId) {

    _filenameDivs[index] = document.getElementById(filenameDivId);
    _fileNames[index] = _filenameDivs[index].innerHTML;
    var picturesDiv = document.getElementById('picturesDiv');
    _outerImageDivs[index] = document.getElementById(outerImageDivId);
    var innerDiv = null;
    _galleryImageIds[index] = galleryImageId;
    _checkBoxes[index] = document.getElementById(checkboxId);
    _checkBoxes[index].disabled = true;


    _onclickScripts[index] = _outerImageDivs[index].getAttribute('onclick');
    _outerImageDivs[index].removeEventListener('click', eval(_onclickScripts[index]), false)
    //_outerImageDivs[index].onclick = _outerImageDivs[index].getAttribute('onclick');

    _textboxDivs[index] = document.createElement('div');
    _textboxDivs[index].className = 'editTextboxDiv';
    _textboxDivs[index].title = 'Filename Editieren';

    _textBoxes[index] = document.createElement('input');
    _textBoxes[index].type = 'text';
    _textBoxes[index].value = _fileNames[index];
    _textBoxes[index].className = 'editTextbox';
    _textBoxes[index].id = filenameDivId;

    saveImage = document.createElement('img');
    saveImage.className = 'saveImage';
    saveImage.src = '/App_Themes/Bytix/img/save.png';
    saveImage.onclick = function() { saveFilename(index); };
    saveImage.setAttribute('alt', 'Speichern');
    saveImage.setAttribute('title', 'Speichern');

    abortImage = document.createElement('img');
    abortImage.className = 'abortEdit';
    abortImage.src = '/App_Themes/Bytix/img/delete.png';
    abortImage.onclick = function() { recreateLabel(true, index); };
    abortImage.setAttribute('alt', 'Abbrechen');
    abortImage.setAttribute('title', 'Abbrechen');


    _textboxDivs[index].appendChild(_textBoxes[index]);
    _textboxDivs[index].appendChild(saveImage);
    _textboxDivs[index].appendChild(abortImage);

    _outerImageDivs[index].removeChild(_filenameDivs[index]);
    _outerImageDivs[index].insertBefore(_textboxDivs[index], _outerImageDivs[index].childNodes[0]);
}


function saveFilename(index) {
    if (_textBoxes[index].value.length == 0) {
        alert('Bitte geben Sie ein Bildname ein.');
    }
    else {
        if (_textBoxes[index].value == _fileNames[index]) {
            recreateLabel(true, index);
        }
        else {
            MobileGallery.AjaxGalleryCallback.UpdateFilename(_galleryProxy.sessionGuid, _galleryImageIds[index], _textBoxes[index].value, index, onSaveFilenameSuccess);

        }
    }
}

function saveGalleryName(galleryId) {
    if (_textBox.value.length == 0) {
        alert('Bitte geben Sie einen Galerie namen ein.');
    }
    else {
        if (_textBox.value == _galleryNameElement.innerHTML) {
            recreateGalleryLabel(true)
        }
        else {
            MobileGallery.AjaxGalleryCallback.UpdateGalleryName(_galleryProxy.sessionGuid, galleryId, _textBox.value, onSaveGalleryNameSuccess);
        }
    }
}

function deleteFiles() {
    if (_galleryImageIds != null) {
        var message = 'Sind Sie sicher dass sie folgende Bilder löschen wollen?\n';
        var files = '';

        for (var i = 0; i <= _galleryImageIds.length; i++) {

            if (_galleryImageIds[i] != null) {
                files += _fileNames[i] + '\n';
            }
        }
        if (files != null) {
            var answer = confirm(message + files);
            if (answer) {
                MobileGallery.AjaxGalleryCallback.DeletePictures(_galleryImageIds, _galleryProxy.sessionGuid, onSuccessfullDeleteImages);
            }
        }
    }
}

function deleteGallery(galleryId, galleryNameDivId) {
    var name = prompt("Bitte geben Sie \"Ja\" ein wenn sie die Galerie \"" + document.getElementById(galleryNameDivId).innerHTML + "\" löschen möchten", "");
    if (name != null && name == "Ja") {
        MobileGallery.AjaxGalleryCallback.DeleteGallery(galleryId, _galleryProxy.sessionGuid, onSuccessfullDeleteGallery);
    }
}

function onSuccessfullDeleteGallery(args) {
    if (args) {
        alert('Galerie erfolgreich gelöscht!');
        window.location = 'default.aspx';
    }
}

function onSuccessfullDeleteImages(args) {
    if (args.length == 0) {
        window.location = 'default.aspx';
    }
    if (args.length > 0) {
        var picturesDiv = document.getElementById('picturesDiv');
        for (var i = 0; i <= args.length; i++) {
            if (args[i] != null && args[i] > 0) {
                _galleryImageIds[i] = null;
                picturesDiv.removeChild(_outerDivs[i]);
                informationToggle(false);
                _searchControlProxy.toggleSearchBoxes(new Array());
            }
        }
    }
}

function onSaveFilenameSuccess(args) {
    if (args >= 0) {
        recreateLabel(false, args);
    }
}

function onSaveGalleryNameSuccess(args) {
    if (args == true) {
        recreateGalleryLabel(false);
    }
}

function recreateLabel(oldFilename, index) {
    _outerImageDivs[index].removeChild(_textboxDivs[index]);
    _filenameDivs[index].className = _filenameDivs[index].className.replace(' highlightFilename', '');
    if (!oldFilename) {
        _filenameDivs[index].innerHTML = _textBoxes[index].value;
    }
    _galleryImageIds[index] = null;

    _fileNames[index] = null;
    _checkBoxes[index].disabled = false;
    _checkBoxes[index].checked = false;
    _outerImageDivs[index].insertBefore(_filenameDivs[index], _outerImageDivs[index].childNodes[0]);
    if (_outerImageDivs[index].addEventListener) {
        _outerImageDivs[index].addEventListener('click', eval(_onclickScripts[index]), false);

    } else if (obj.attachEvent) {
        _outerImageDivs[index].attachEvent('onclick', eval(_onclickScripts[index]));
    }
    _onclickScripts[index] = null;
}

function recreateGalleryLabel(oldFilename) {


    _galleryNameDiv.insertBefore(_galleryNameElement, _galleryNameDiv.childNodes[0]);
    _deleteGalleryDiv.style.display = "";
    _galleryNameDiv.removeChild(_textBoxDiv);
    if (!oldFilename) {
        _galleryNameElement.innerHTML = _textBox.value;
    }

    setTimeout(function() { _galleryNameDiv.onclick = function() { eval(_onClickScript); }; }, 300);
}


function addErrorMessage(error) {
    _galleryProxy.errorLabel.innerHTML = error;
}
