﻿/// <reference path="jquery-1.3.vsdoc.js" />
var bMovePhoto = true; //determines if photo should be moved to FTP
var bIsThread = false;
var bNewAvatar = false;
var bIsEdited = false;
var bAddToAnotherType = false;
var bCategoryTreeDisabled = false;
var type; // type of photo - place,object,event
var result_html = null; //html with multiple search results
var zoom_for_accuracy = [17, 12, 8, 6, 4, 3, 1, 0, 0];
var close_st = "<a href='#' style='float: right' id='qc_close'>" + '[Zamknij]' + "</a>";
var placemarks = null; //needed when google gives many search results
var address = "";
var search_working_mode = "default";
var iGoogleResults = 0;
var googlePlace = null;
var placeId;
var iCityId = -1;
var CityPlacemark;
var iStreetId = -1;
var StreetPlacemark;
var iHouseId = -1;
var HousePoint;
var CityName;
var StreetName;
var iCategoryId;
var iStep = 0;
var dpPhoto;
var sReturnUrl = "";
var iDivTempId = -1; //for floatdialog window
var arrTypeRB = $("input[id*='rbPhoto']");
var saveHref; // to rember postback when disabling linkbutton

function initializeUpload() {

    var divPhoto = $("#divPhoto");
    var hintPlace = $("#hintPlace");
    type = $("[id$=m_hidType]").val();
    $("input[name$='placeToFind']").keypress(function(e) {
        if (e.which == 13) {
            showLocation();
            return false;
        }
    });
    if (bIsThread) {
        $("#description-div").show();
        if (type == null || type == "") {
            $("#divType").show();
        }
    }
    else {
        dpPhoto = new datePanel($("#date-div"));
    }
    map_working_mode = "upload";
    search_working_mode = "upload";
    placeId = $("[id$=m_hidPlaceId]").val();
    var lt = parseFloat($("[id$=m_hidMapLat]").val());
    var ln = parseFloat($("[id$=m_hidMapLng]").val());
    if (type != "") {
        if (dpPhoto!= null && $("[id$=m_hidDateFrom]").val() != "") {
            dpPhoto.setValues($("[id$=m_hidDateFrom]").val(), $("[id$=m_hidDateTo]").val(), $("[id$=m_hidDateType]").val(), '.');
        }
        if (type == "Event") {
            handleTypeEvent();
        }
        else if (type == "Object") {
            handleTypeObject();
            handleRbPhoto('rbPhoto2');
        }
        else if (type == "Album") {
            handleTypeAlbum();
        }
        else {
            $("#divHintChoosePhoto").html("<p>Wybierz zdjęcie z poczekalni, lub dodaj nowe. Pola typu zdjęcia oraz lokalizacji zostały już wypełnione.</p>");
            handleTypePlace(lt, ln, 13); //TODO : get zoom
            handleRbPhoto('rbPhoto1');
        }
        divPhoto.show();
        hintPlace.hide();
        $("#btNextStep").hide();
        $("#divSave").show();
        $("#SaveAndContinueButton").hide();
        arrTypeRB.attr("disabled", "disabled");
    }
    if (placeId != "" || type == "event") {
        map_working_mode = "disabled";
        $("[id$=m_fsSearch]").hide();
        $("[id$=inHouseNumber]").attr("disabled", "disabled");
        var sTypeToUrl = "";
        switch (type){
            case "City": 
                sTypeToUrl  = "miasto";
                break;
            case "Street":
                sTypeToUrl  = "ulica";
                break;
            case "House":    
                sTypeToUrl  = "dom";
                break;
        } 
        sReturnUrl = path + "/" + sTypeToUrl + "/" + placeId + "/" + $("[id$=m_hidPlaceName]").val();
    }
    else if ($("[id$=m_hidCategoryId]").val() != "" && $("[id$=m_hidCategoryId]").val() != "-1") {
        setCategoryId($("[id$=m_hidCategoryId]").val());
        bCategoryTreeDisabled = true;
        $("[id$=divCategory]").show();
        if ($("[id$=rbPhoto2]:checked").length > 0)
            sReturnUrl = path + "/przedmioty/kategoria" + iCategoryId;
        else
            sReturnUrl = path + "/wydarzenia/kategoria" + iCategoryId;
    }
    var photoId = $("[id$=m_hidPhotoId]").val();
    if (photoId != "" && !bIsThread) {
        bIsEdited = true;
        sReturnUrl = path+"/profil/zdjecia";
        $("#liHeader").attr("class", "hdr h-edit-photo");
        iCategoryId = parseInt($("[id$=m_hidCategoryId]").val());
        bMovePhoto = false;
        bCategoryTreeDisabled = false;
        setCategoryId(iCategoryId);
        $("#divHintChoosePhoto").hide();
        $(".add-steps").hide();
        $(".add-new").hide();
        $("#h3ChoosePhoto").hide();
        hintPlace.show();
        $("#description-div").show();
        $("#SaveAndContinueButton").show();
        $("#TempId").val(photoId);
        divPhoto.show();
    }
    if (!isNaN(lt) && !isNaN(ln)) {
        var gmarker = createGMarker(new GLatLng(lt, ln), false, getIconType(type));
        gmarker.cityid = $("[id$=m_hidCityId]").val();
        gmarker.streetid = $("[id$=m_hidStreetId]").val();
        gmarker.houseid = $("[id$=m_hidHouseId]").val();
        gmarker.type = type;
        selectedMarker = gmarker;
        map.addOverlay(gmarker);
    }
    if ($("[id$=hidGroupId]").length > 0 && $("[id$=hidGroupId]").val() != "-1") {
        $("#rbPhoto4").attr("checked", "checked");
        nextStep();
    }
    //setupValidation(); TODO: turn on javascript validation

    //if(!$.browser.msie &&  !parseInt($.browser.version) == 6)
    $("[id$=imgEditedPicture]").bind("mouseover", showLargePhoto);

}

function clearForm() {
    if (map != null)
        map.clearOverlays();
    selectedMarker = null;
    bMovePhoto = true;
    iStep = 0;
    clearDivPhoto();
    $("[id$=inCity]").val("");
    $("[id$=inStreet]").val("");
    $("[id$=inHouseNumber]").val("");
    $("input[id*=m_inTags]").val("");
    $("[id*=rbPhoto]").show();
    $("[id*=labType]").show();
    $("[id$=Description]").val("").removeAttr("disabled");
    iCityId = -1;
    CityPlacemark = null;
    iStreetId = -1;
    StreetPlacemark = null;
    iHouseId = -1;
    HousePoint = null;
    bCategoryTreeDisabled = false;
    $("#spanFirst").attr("class", "first current1");
    $("#spanSecond").attr("class", "second");
    $("#spanThird").attr("class", "third");
}
function clearDivPhoto() {
    $("input[id*=m_inTitle]").val("");
    $("[id*=m_taDescriptionArea]").val("");
    $("[id*=m_taTags]").val("");
    if (dpPhoto != null)
        dpPhoto.reset();

}
function hideAll() {
    $("#SaveButton").removeAttr("disabled");
    $("#SaveAndContinueButton").removeAttr("disabled");
    $("#btNextStep").show();
    if (!bIsThread) {
        $("#description-div").hide();
    }
    $("[id$=divCategory]").hide();
    $("#divPlace").hide();
    $("#divPhoto").hide();
    $("#divSave").hide();
    $("#btPrevStep").hide();
}
function selectPlace(city, street, house, lat, lng, disable) {
    $("[id$=inCity]").val(city);
    $("[id$=inStreet]").val(street);
    $("[id$=inHouseNumber]").val(house);
}
function showLargePhoto() {
    if ($("[id$=imgEditedPicture]").attr('src') != "../_pic/default_place_m.png") {
        $("#imgEnlargedPicture").attr('src', $("[id$=imgEditedPicture]").attr('src').replace("mini", "normal"));
        $(".swfupload").hide();
        //$("#divEnlargedPicture").css('left',width);
        $("#divEnlargedPicture").show();
    }
}

function setupValidation() {
    $("#aspnetForm").validate({
        rules: {
            CreatedDate: {
                required: false //"#rb1:checked",
            },
            Year: {
                required: false, //"#rb2:checked",
                number: true,
                minlength: 4,
                maxlength: 4
            },
            YearFrom: {
                required: false, //"#rb3:checked",
                number: true,
                minlength: 4,
                maxlength: 4
            },
            YearTo: {
                required: false, //"#rb3:checked",
                number: true,
                minlength: 4,
                maxlength: 4
            },
            Title: {
                required: function(element) {
                    return $("#divPhoto:visible").length > 0;
                },
                maxlength: 55
            },
            DescriptionArea: {
                maxlength: 10000
            },
            Street: {
                maxlength: 45
            },
            City: {
                required: function(element) {
                    return $("[id$=rbPhoto1]:checked").length > 0;
                },
                maxlength: 45
            },
            HouseNumber: {
                min: 1
            },
            Tags: {
                maxlength: 100
            }
        },
        messages: {
            CreatedDate: {
                required: "Musisz podać datę zrobienia zdjęcia!",
                date: "Nieprawidłowa data!"
            },
            Title: {
                required: "Musisz podać tytuł!",
                maxlength: "Za długi tytuł!"
            },
            DescriptionArea: {
                maxlength: "Za długi opis!"
            },
            Year: {
                required: "Musisz podać rok zrobienia zdjęcia",
                number: "Nieprawidłowa data!",
                minlength: "Nieprawidłowa data!",
                maxlength: "Nieprawidłowa data!"
            },
            YearFrom: {
                required: "Musisz podać rok",
                number: "Nieprawidłowa data!",
                minlength: "Nieprawidłowa data!",
                maxlength: "Nieprawidłowa data!"
            },
            YearTo: {
                required: "Musisz podać rok",
                number: "Nieprawidłowa data!",
                minlength: "Nieprawidłowa data!",
                maxlength: "Nieprawidłowa data!"
            },
            Street: {
                maxlength: "Za długa nazwa ulicy"
            },
            City: {
                required: "Musisz podać miejscowość",
                maxlength: "Za długa nazwa miejscowości"
            },
            HouseNumber: {
                min: "Nieprawidłowy numer"
            },
            Tags: {
                maxlength: "Za długa lista tagów"
            }
        }
    });
}
function isHouseNumberInDb(response) {
    StreetName = getStreet(googlePlace);
    CityName = getCity(googlePlace);
    if (response.Houses != null && response.Houses.length>0) {
        iHouseId = response.Houses[0].houseid;
        geocoder.getLocations(googlePlace.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName + " " + getCity(googlePlace),
                    function(response) {
                        CityPlacemark = response.Placemark[0];
                    }

                );
        geocoder.getLocations(googlePlace.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName + " " + getCity(googlePlace) + " " + getStreet(googlePlace),
                    function(response) {
                        StreetPlacemark = response.Placemark[0];
                    }

                );

    }
    else {
        // there is no house number in database
        HousePoint = selectedMarker.getLatLng();
    }
    if ($("[id$=m_hidID]").val() != "" && window.location.href.indexOf("/grupa/") != -1) {
        place.saveAssignGroup(parseInt($("[id$=m_hidID]").val()));
    }
    else {
        save();
    }
}
function save() {
    $("#SaveButton").attr("disabled", "true");
    $("#SaveAndContinueButton").attr("disabled", "true");

    var ltln = new GLatLng(90, 90);
    if (selectedMarker != null) {
        switch (selectedMarker.type) {
            case "miasto": iCityId = selectedMarker.cityid;
                break;
            case "ulica":
                iStreetId = selectedMarker.streetid;
                iCityId = selectedMarker.cityid;
                break;
            case "dom":
                iHouseId = selectedMarker.houseid;
                iStreetId = selectedMarker.streetid;
                if (selectedMarker.cityid != null) {
                    iCityId = selectedMarker.cityid;
                }
                break;
        }
        ltln = selectedMarker.getLatLng();
    }
    //if ($("#aspnetForm").valid()) {
    var postUrl;
    if (bIsThread) {
        postUrl = path + "/Thread/SaveThread.aspx"
        $.ajax({
            type: "POST",
            url: postUrl,
            dataType: "json",
            success: onSuccessSave,
            error: onErrorSave,
            data: {
                Title: $("input[id*=m_inTitle]").val(),
                Description: $("[id*=m_taDescriptionArea]").val(),
                Lat: ltln.lat(),
                Lng: ltln.lng(),
                HouseNumber: $("[id$=inHouseNumber]").val(),
                Type: photoType,
                FinishEdit: !bAddToAnotherType,
                CatId: iCategoryId,
                CityId: iCityId,
                StreetId: iStreetId,
                HouseId: iHouseId,
                GroupId: $("input[id$=m_hidGroupId]").val(),
                CityLat: (CityPlacemark == null) ? null : CityPlacemark.Point.coordinates[1],
                CityLng: (CityPlacemark == null) ? null : CityPlacemark.Point.coordinates[0],
                CityZoom: (CityPlacemark == null) ? null : getZoom(CityPlacemark),
                StreetLat: (StreetPlacemark == null) ? null : StreetPlacemark.Point.coordinates[1],
                StreetLng: (StreetPlacemark == null) ? null : StreetPlacemark.Point.coordinates[0],
                StreetZoom: (StreetPlacemark == null) ? null : getZoom(StreetPlacemark),
                HouseLat: (HousePoint == null) ? null : HousePoint.lat(),
                HouseLng: (HousePoint == null) ? null : HousePoint.lng(),
                CityName: CityName,
                StreetName: StreetName
            }
        });
    }
    else {
        postUrl = path + "/Photo/SavePhoto.aspx"
        $.ajax({
            type: "POST",
            url: postUrl,
            dataType: "json",
            success: onSuccessSave,
            error: onErrorSave,
            data: {
                Title: $("input[id*=m_inTitle]").val(),
                Description: $("[id*=m_taDescriptionArea]").val(),
                IsForSale: $("[id$=m_chbForSale]").is(":checked"),
                AddWaterMark: $("[id$=m_chbAddWaterMark]").is(":checked"),
                VisibleFor: $("[id$=m_ddlVisibleFor]")[0].selectedIndex,
                TempId: $("#TempId").val(),
                CreatedFrom: dpPhoto.getFromValue(),
                CreatedTo: dpPhoto.getToValue(),
                DateType: dpPhoto.getTypeOfDates(),
                Tags: $("input[id*=m_inTags]").val(),
                PhotoPrice: $("[id$=m_inPrice]").val(),
                Lat: ltln.lat(),
                Lng: ltln.lng(),
                HouseNumber: $("[id$=inHouseNumber]").val(),
                IsObjectForSale: $("[id$=m_chbObjectForSale]").is(":checked"),
                ObjectPrice: $("[id$=m_inObjectPrice]").val(),
                Type: photoType,
                FinishEdit: !bAddToAnotherType,
                CatId: iCategoryId,
                CityId: iCityId,
                StreetId: iStreetId,
                HouseId: iHouseId,
                CityLat: (CityPlacemark == null) ? null : CityPlacemark.Point.coordinates[1],
                CityLng: (CityPlacemark == null) ? null : CityPlacemark.Point.coordinates[0],
                CityZoom: (CityPlacemark == null) ? null : getZoom(CityPlacemark),
                StreetLat: (StreetPlacemark == null) ? null : StreetPlacemark.Point.coordinates[1],
                StreetLng: (StreetPlacemark == null) ? null : StreetPlacemark.Point.coordinates[0],
                StreetZoom: (StreetPlacemark == null) ? null : getZoom(StreetPlacemark),
                HouseLat: (HousePoint == null) ? null : HousePoint.lat(),
                HouseLng: (HousePoint == null) ? null : HousePoint.lng(),
                CityName: CityName,
                StreetName: StreetName,
                IsEdited: bIsEdited,
                MovePhoto: bMovePhoto
            }
        });
    }

    function onSuccessSave(response, statusText) {
        if (response.ok) {
            hideAll();
            arrTypeRB.removeAttr("disabled");
            if (sReturnUrl != "" && !bAddToAnotherType) {
                if (history.length > 1) {
                    window.location = document.referrer;
                }
                else {
                    window.location = sReturnUrl;
                }
            }
            else {
                if (bAddToAnotherType) {
                    addToAnotherType();
                }
                else {
                    if (!bIsThread) {
                        
                        var tempId = $("#TempId").val();
                        $("#tempPhoto" + tempId).hide();
                        $(".no-results").hide();
                        __doPostBack("ctl00_Main_m_upUserPhotos", response.status);
                        clearForm();
                        $("[id$=imgEditedPicture]").attr('src', "../_pic/default_place_m.png");
                        $("#description-div").hide();
                        showAllRb();
                    }
                    else {
                        window.location = path + "/watek/" + response.id;
                    }
                }
            }
            status.showInfo(response.status);
        }
        else {
            status.showError(response.status);
            onErrorSave();
        }
    };
    function onErrorSave(xhr, textStatus, errorThrown) {
        $("#SaveButton").removeAttr("disabled");
        $("#SaveAndContinueButton").removeAttr("disabled");
        //    $("#btNextStep").show();
        window.location.hash = "settings";
    };
    
    return false;
}
function submitPhoto() {
    if ($("[id$=rbPhoto1]:checked").length > 0 && selectedMarker == null) {
        status.showError('Musisz zaznaczyć miejsce na mapie');
        return false;
    }
    if ($("[id$=rbPhoto1]:checked").length > 0 && placeId == "" && $("[id$=inHouseNumber]").val() != "") {
        //user saves new House
        HousePoint = selectedMarker.getLatLng();
        if ($("[id$=inStreet]").val() == "") {
            $.getJSON(encodeURI(path+"/Place/GetPlaces.aspx?house=" + $("[id$=inHouseNumber]").val() + "&cityid=" + iCityId), isHouseNumberInDb);
        }
        else {
            $.getJSON(encodeURI(path+"/Place/GetPlaces.aspx?house=" + $("[id$=inHouseNumber]").val() + "&streetid=" + iStreetId), isHouseNumberInDb);
        }
    }
    else {
        save();
    }
}

function cancelSubmit() {
    arrTypeRB.removeAttr("disabled");
    arrTypeRB.attr("checked", false);
    $("[id$=imgEditedPicture]").attr('src', "../_pic/default_place_m.png");
    clearForm();
    hideAll();
    if (sReturnUrl != "")
        window.location = sReturnUrl;

}
var photoType = 0;
function handleRbPhoto(rbId) {
    arrTypeRB.removeAttr("checked");
    $("[id$=" + rbId + "]").attr("checked", "checked");
}
function prevStep() {
    iStep--;
    hideSaveDiv();
    step(true);
}
function nextStep() {
    iStep++;
    step();
}
function step(bPrev) {
    switch (iStep) {
        case 0:
            $("#divPlace").hide();
            $("#divType").show();
            $("[id$=divCategory]").hide();
            $("#divPhoto").hide();
            arrTypeRB.removeAttr("disabled");
            $("#btNextStep").show();
            $("#btPrevStep").hide();
            clearForm();
            break;
        case 1:
            if (bPrev && $("[id$=rbPhoto4]").is(':checked')) {
                prevStep();
            }
            else if ($("input[id*='rbPhoto']:checked").length > 0) {
                $("td[class=selected]").removeAttr("class", "selected").attr("class", "normal");
                $("table[class=active]").removeAttr("class", "active");
                $("#btPrevStep").show();
                $("[id$=divCategory]").hide();
                $("#divOriginalForSale").show();
                $("#divPhoto").hide();
                $("#divPlace").hide();
                $("[id*=hlOmit]").show();
                $("[id$=Description]").val("").removeAttr("disabled");
                $("#divType").hide('slow');
                arrTypeRB.attr("disabled", "disabled");
                $("#divVisibleFor").hide();
                if ($("[id$=rbPhoto1]").is(':checked')) {
                    $("#spanObligatoryDate").hide();
                    handleTypePlace();
                }
                else if ($("[id$=rbPhoto2]").is(':checked')) {
                    $("#spanObligatoryDate").show();
                    $("input[name='rbPhoto1']").attr('checked', false);
                    handleTypeObject();
                }
                else if ($("[id$=rbPhoto3]").is(':checked')) {
                    $("#spanObligatoryDate").hide();
                    $("input[name='rbPhoto1']").attr('checked', false);
                    handleTypeEvent();
                }
                else {
                    iStep++;
                    $("#spanObligatoryDate").show();
                    handleTypeAlbum()
                    nextStep();
                }
            }
            else {
                alert('Musisz wybrać typ zdjęcia');
            }
            break;
        case 2:
            $("#divPhoto").hide();
            if (bPrev) {
                prevStep();
            }
            else {
                if (photoType == 1 || photoType == 2) {
                    //event - phase 2,object - phase 2
                    if ($("[id$=divCategory]").is(':visible') && $("[id$=rbPhoto2]").is(':checked')) {
                        //object - phase 2
                        showSaveDiv();
                        //CAUTION!!! check what's going on when user edit photo
                        $("[id$=divCategory]").hide(); // HIDE PREV STEP LS IDEA;)
                        $("#divPhoto").show();
                        $("#spanSecond").attr("class", "second");
                        $("#spanThird").attr("class", "third current3");
                    }
                    if (photoType == 2 && ($("[id$=divCategory]").is(':visible')) || (bPrev && photoType != 3)) {
                        //event -phase 3
                        $("[id$=divSkipPlace]").show();
                        $("#divPlace").show();
                        $("[id$=divCategory]").hide();
                        $("#divPhoto").hide();
                        setupMap(true);
                    }
                }
                else {
                    stepPlace();
                }
            }
            break;
        case 3:
            if (bPrev)
                prevStep();
            else
                nextStep();
            break;
        case 4:
            //place -phase 2 event -phase 3
            stepPlace();
            showSaveDiv();
            break;
    }
    $("#fldActions").show();
}
function hideSaveDiv() {
    $("#divSave").hide();
    $("#btNextStep").show();
}
function showSaveDiv() {
    $("#divSave").show();
    $("#btNextStep").hide();
}
function stepPlace() {
    if (selectedMarker == null) {
        if ($("[id$=rbPhoto1]").is(':checked')) {
            alert('Musisz wybrać lokalizację');
            return;
        }
        else {
            $("#divPlace").hide();
        }
    }
    //if (bMovePhoto) {            //CAUTION!!! check what's going on when user edit photo
    $("#divPlace").hide(); // HIDE PREV STEP LS IDEA;)
    $("#divPhoto").show();
    $("#spanSecond").attr("class", "second");
    $("#spanThird").attr("class", "third current3");
    //}
    $("#divSave").show();
    $("#btNextStep").hide();

}
function handleTypePlace(lat, lng, zoom) {
    photoType = 0;
    changeText("place");
    $("[id$=divSkipPlace]").hide();
    $("#description-div").show();
    $("#divPlace").show();
    setupMap(true, lat, lng, zoom);
}
function handleTypeObject() {
    photoType = 1;
    changeText("object");
    $("input[name='rbPhoto3']").attr('checked', false);
    $("#divPlace").hide();
    $("input[name='rbPhoto1']").attr('checked', false);
    $("#divObjectForSale").show();
    $("#divOriginalForSale").hide();
    $("div[name=ObjectCat]").show();
    $("div[name=EventCat]").hide();
    $("[id$=divCategory]").show();
}
function handleTypeEvent() {
    photoType = 2;
    changeText("event");
    $("div[name=ObjectCat]").hide();
    $("div[name=EventCat]").show();
    $("input[name='rbPhoto2']").attr('checked', false);
    $("[id$=divCategory]").show();
}
function handleTypeAlbum() {
    photoType = 3;
    changeText("albums");
    $("#divVisibleFor").show();
}
function setCategoryId(iCatId) {
    if (!bCategoryTreeDisabled) {
        $("a[href$=setCategoryId(" + iCategoryId + ")]").parent().attr("class", "normal"); //remove old selection
        iCategoryId = iCatId;
        $("a[href$=setCategoryId(" + iCatId + ")]").parent().attr("class", "selected");
        $("table[class*=active]").attr("class", "");
        $("td[class*=selected]").parent().parent().parent().attr("class", "active"); //FOR GRAPHIC
    }
    else {
        $("a[href$=setCategoryId(" + iCatId + ")]").parent().removeAttr("class", "selected"); //remove old selection
    }
}

function redescribe() {
    $("div[id$='divRedescribe']").hide();
    cancelSubmit();
    describePhoto(iDivTempId);
    return false;
}

function floatDialogHandler(id) {
    if ($("#description-div").is(':visible') && type == null) {
        $("[id*=tempPhotoIdHref]").unbind();
        $("[id*=tempPhotoIdHref]").removeAttr("onclick");
        $("[id*=tempPhotoIdHref]").floatdialog("divRedescribe");
        $("[id*=tempPhotoIdHref]").click();
        return false;
    }
    else {
        $("[id*=tempPhotoIdHref]").click(function() {
            $("[id*=tempPhotoIdHref]").unbind();
        });
    }
    return true;
}

function describePhoto(id) {
    iDivTempId = id;
    if (type == null) {
        $("#upload-finished-div").hide();
    }
    if (floatDialogHandler(id)) {
        if (map_working_mode != "disabled") {
            $("#spanFirst").attr("class", "first");
            $("#spanSecond").attr("class", "second current2");
            $("#description-div").show('slow');
            $("#divType").show();
            $("#date-div").show();
            $("input[id*=m_inTags]-div").show();
        }
        $("#TempId").val(id);
        $("[id$=imgEditedPicture]").attr('src', ($("a[id=tempPhoto" + id + "]").children().attr('src').replace("micro", "mini")));
    }
    return false;
}
function addToAnotherType() {
    bMovePhoto = false;
    $("#description-div").show();
    $("#divType").show();
    iStep = 0;
    if ($("[id$=rbPhoto1]:checked").length > 0) {
        hideType(1);
    }
    else if ($("[id$=rbPhoto2]:checked").length > 0) {
        hideType(2);
    }
    else if ($("[id$=rbPhoto3]:checked").length > 0) {
        hideType(1);
        hideType(3);
    }
    else {
        hideType(4);
    }
    $("input[id^='rbPhoto']").removeAttr("checked");
    if ($("input[id^='rbPhoto']:visible").length == 1) {
        $("input[id^='rbPhoto']:visible").attr("checked", true);
        $("#SaveAndContinueButton").hide();
        nextStep();
    }
    return false;
}
function hideType(typeId) {
    $("[id$=rbPhoto" + typeId + "]").hide();
    $("[id$=labType" + typeId + "]").hide();
    $("#divPhoto").hide();
    $("#divSave").hide();
}

function showAllRb() {
    arrTypeRB.show();
    arrTypeRB.attr("checked", false);
    $("[id*=labType]").show();
}

function showLocation() {
    iGoogleResults = 0;
    closeResults();
    iCityId = -1;
    iStreetId = -1;
    iHouseId = -1;
    result_html = "<ul>";
    address = $('input[name$=placeToFind]').val();
    saveHref = $('a[id$=m_lbSaveAboutAndLocalization]').attr('href');
    $('a[id$=m_lbSaveAboutAndLocalization]').removeAttr('href');
    geocoder.getLocations(address, addAddressToMap);

    return false;
}
// addAddressToMap() is called when the geocoder returns an answer.  
function addAddressToMap(response) {

    if (!response || response.Status.code != 200) {
        //no results
    }
    else if (response.Placemark.length == 1) {
        //one place found by google
        googlePlace = response.Placemark[0];
        if (getStreet(googlePlace) !== "") {
            // user entered street and city(and maybe house)
            var url = path + "/Place/GetPlaces.aspx?city=" + getCity(googlePlace) + "&street=" + getStreet(googlePlace);
            url = encodeURI(url);
            $.getJSON(url, checkDbResults)
        }
        else {
            //user entered only city
            $.getJSON(encodeURI(path + "/Place/GetPlaces.aspx?city=" + getCity(googlePlace)), checkDbResults)
        }
        iGoogleResults++;
    }
    else {
        placemarks = response.Placemark;
        for (var i = 0; i < response.Placemark.length; i++) {
            iGoogleResults++;
            buildGoogleResultLink(response.Placemark[i], i);
        }

    }
    if (search_working_mode == "upload" || search_working_mode == "user_location") {
        handleResults();
    }
    else {
        $.getJSON("Photo/GetPhotos.aspx?t=tag&tag=" + address, prepareResults)
    }
}
function checkDbResults(response) {
    StreetName = getStreet(googlePlace);
    CityName = getCity(googlePlace);

    if (response.Found) {
        if (response.Streets != null) {
            iCityId = response.Cities[0].cityid;
            iStreetId = response.Streets[0].streetid;
        }
        else {
            iCityId = response.Cities[0].cityid;
            if (getStreet(googlePlace) !== "") {
                geocoder.getLocations(googlePlace.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName + " " + getCity(googlePlace),
                    function(response) {
                        CityPlacemark = response.Placemark[0];
                        setCityLatLng();
                    }

                );
                if (getHouseNumber(googlePlace) == "") {
                    StreetPlacemark = googlePlace;
                    setStreetLatLng();
                }
                else {
                    geocoder.getLocations(googlePlace.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName + " " + getStreet(googlePlace),
                    function(response) {
                        StreetPlacemark = response.Placemark[0];
                        setStreetLatLng();
                    }

                    );
                }
            }
            else {
                CityPlacemark = googlePlace;
                setCityLatLng();
            }
        }
    }
    else {
        // there is no city and street in database
        if (getStreet(googlePlace) != "") {
            geocoder.getLocations(googlePlace.AddressDetails.Country.CountryName + ', ' + googlePlace.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName + ', ' + getCity(googlePlace),
                    function(response) {
                        CityPlacemark = response.Placemark[0];
                        setCityLatLng();
                    }

                );
            if (getHouseNumber(googlePlace) == "") {
                StreetPlacemark = googlePlace;
                setStreetLatLng();
            }
            else {
                geocoder.getLocations(googlePlace.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName +
                        ", " + getCity(googlePlace) + ", " + getStreet(googlePlace),
                        function(response) {
                            StreetPlacemark = response.Placemark[0];
                            setStreetLatLng();
                        }
                    );
            }
        }
        else {
            CityPlacemark = googlePlace;
            setCityLatLng();
        }
    }
    $('a[id$=m_lbSaveAboutAndLocalization]').attr('href', saveHref);
    $("[id$=CityId]").val(iCityId);
    $("[id$=StreetId]").val(iStreetId);
    $("[id$=HouseId]").val(iHouseId);
    $("[id$=CityName]").val(CityName);
    $("[id$=StreetName]").val(StreetName);
}
function setCityLatLng() {
    $("[id$=CityLat]").val((CityPlacemark == null) ? null : CityPlacemark.Point.coordinates[1]);
    $("[id$=CityLng]").val((CityPlacemark == null) ? null : CityPlacemark.Point.coordinates[0]);
    $("[id$=CityZoom]").val((CityPlacemark == null) ? null : getZoom(CityPlacemark));
}
function setStreetLatLng() {
    $("[id$=StreetLat]").val((StreetPlacemark == null) ? null : StreetPlacemark.Point.coordinates[1]);
    $("[id$=StreetLng]").val((StreetPlacemark == null) ? null : StreetPlacemark.Point.coordinates[0]);
    $("[id$=StreetZoom]").val((StreetPlacemark == null) ? null : getZoom(StreetPlacemark));
}
function googleResultHandler(lt, ln, zoom, city, street, house, placemarkId) {
    map.setCenter(new GLatLng(parseFloat(lt), parseFloat(ln)), zoom);
    if (search_working_mode == "upload" || search_working_mode == "user_location") {
        createOwnMarker(new GLatLng(parseFloat(lt), parseFloat(ln)), getTypeFromGoogleSearch(city, street, house));
        if (iGoogleResults > 1) {
            //assign place that user choose
            googlePlace = placemarks[placemarkId];
        }
        selectPlace(city, street, house, lt, ln, false);
        if (iGoogleResults > 1) {
            //            $.getJSON(encodeURI(path+"/Place/GetPlaces.aspx?city=" + city + "&lat=" + lt + "&lng=" + ln), checkDbResults)
            if (getStreet(googlePlace) !== "") {
                // user entered street and city(and maybe house)
                var url = path + "/Place/GetPlaces.aspx?city=" + getCity(googlePlace) + "&street=" + getStreet(googlePlace);
                url = encodeURI(url);
                $.getJSON(url, checkDbResults)
            }
            else {
                //user entered only city
                $.getJSON(encodeURI(path + "/Place/GetPlaces.aspx?city=" + getCity(googlePlace)), checkDbResults)
            }
        }
    }
}
function buildGoogleResultLink(placemark, placemarkId) {
    googlePlace = placemark;
    var a = googlePlace.address;
    var point = googlePlace.Point;
    var acc = googlePlace.AddressDetails ? googlePlace.AddressDetails.Accuracy : 8;
    var z = 17 - zoom_for_accuracy[Math.max(Math.min(acc, 8), 0)];

    result_html += "<li><a href='#' onclick='googleResultHandler(" + point.coordinates[1] + "," + point.coordinates[0] + "," + z +
            ",\"" + getCity(googlePlace) + "\",\"" + getStreet(googlePlace) + "\",\"" + getHouseNumber(googlePlace) + "\",\"" + placemarkId + "\"); "
            + "closeResults(); return false;'>" +
                a.replace("<", "&lt;").replace(">", "&gt;") +
                "</a></li>";
}
function closeResults() {
    $("#results").hide("slow");
}
function encode_utf8(s) {
    return unescape(encodeURIComponent(s));
}

function decode_utf8(s) {
    return decodeURIComponent(escape(s));
}
function handleResults() {
    if (iGoogleResults == 0) {
        $("#results").html('Nie możemy znaleźć <em>%slider</em>.'.replace("%slider", $('input[name$=placeToFind]').val()) + close_st).show("slow");
        $('a[id$=m_lbSaveAboutAndLocalization]').attr('href', saveHref);
        $("#qc_close").click(function() { $(this).parent().hide('normal'); return false; });
    }
    else if (iGoogleResults == 1) {

        var point = googlePlace.Point;
        var acc = googlePlace.AddressDetails ? googlePlace.AddressDetails.Accuracy : 8;
        var z = 17 - zoom_for_accuracy[Math.max(Math.min(acc, 8), 0)];

        googleResultHandler(point.coordinates[1], point.coordinates[0], z,
                        getCity(googlePlace), getStreet(googlePlace), getHouseNumber(googlePlace));

    }
    else {
        $("#results").html(result_html).show("slow");
        $("#qc_close").click(function() { $(this).parent().hide('normal'); return false; });
    }
}
function getZoom(place) {
    var acc = place.AddressDetails.Accuracy;
    return 17 - zoom_for_accuracy[Math.max(Math.min(acc, 8), 0)];
}
function getCity(place) {
    if (place != null && place.AddressDetails.Country != null && place.AddressDetails.Country.AdministrativeArea != null) {
        if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null)
            return place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
        else if (place.AddressDetails.Country.AdministrativeArea.Locality != null)
            return place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
        else return "";
    }
    else if (place.address != null) {
        //maybe this IF will be enough for city?? 
        return place.address.substring(0, place.address.lastIndexOf(','));
    }
    else
        return "";
}
function getStreet(place) {
    var sStreetAndHouse = getStreetAndHouse(place);
    var asStreetAndHouse = sStreetAndHouse.split(' ');
    if (gotNum(asStreetAndHouse[asStreetAndHouse.length - 1])) {
        return sStreetAndHouse.substring(0, sStreetAndHouse.lastIndexOf(' '));
    }
    else {
        return sStreetAndHouse;
    }
}
function getHouseNumber(place) {
    var sStreetAndHouse = getStreetAndHouse(place);
    var asStreetAndHouse = sStreetAndHouse.split(' ');
    if (gotNum(asStreetAndHouse[asStreetAndHouse.length - 1])) {
        return asStreetAndHouse[asStreetAndHouse.length - 1];
    }
    else {
        return "";
    }
}
function getStreetAndHouse(place) {
    if (place != null && place.AddressDetails.Country != null && place.AddressDetails.Country.AdministrativeArea != null) {
        if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea != null &&
                place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null
                && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare != null)
            return place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
        else if (place.AddressDetails.Country.AdministrativeArea.Locality != null
                    && place.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare != null)
            return place.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
    };
    return "";
};
function gotNum(str) {
    return /\d/.test(str);
}
function changeText(type) {
    $("[id$=labTitle]").html("Tytuł");
    $("#h3Describe").html("Opisz&nbsp;zdjęcie");
    $("#divOrgForSale").show();
    $("#divObjForSale").hide();
    $("#pDescribe").html("Podaj kiedy zostało wykonane zdjęcie, zatytułuj je oraz opisz co przedstawia. Jeśli nie znasz dokładnej daty, możesz podać rok lub przedział lat. Dobry i zwięzły tytuł zdjęcia, jak również tagi ułatwią innym użytkownikom odnalezienie go w serwisie.");
    if (type == "place") {
        if (bIsThread)
            $("#hintLocalization").html("<span>Uwaga!</span>po wyborze lokalizacji dyskusja zostanie automatycznie dodana również do kategorii MIEJSCE.");
    }
    else if (type == "object") {
        $("#divOrgForSale").hide();
        $("#divObjForSale").show();
        if (!bIsThread)
            $("[id$=labTitle]").html("Nazwa");
        $("#h3Describe").html("Opisz przedmiot na zdjęciu");
        $("#pDescribe").html("Podaj dokładną nazwę przedmiotu oraz, z jakiego okresu pochodzi. Możesz również dodać opis przedmiotu. Pamiętaj, że wpisując tagi ułatwisz innym użytkownikom odnalezienie zdjęcia Twojego przedmiotu w serwisie.");
        $("#hintForSale").html("Tamte Czasy dają Ci możliwość sprzedania zarówno papierowej wersji zdjęcia, które dodajesz do serwisu, jak również przedmiotu, który jest na zdjęciu. Wystarczy, że zaznaczysz teraz opcję „Oryginał zdjęcia na sprzedaż” lub „Przedmiot na sprzedaż” oraz podasz jego cenę, a informacja o Twojej ofercie będzie widoczna obok zdjęcia.");
        if (bIsThread)
            $("#hintCategoryType").html("Przedmioty posegregowaliśmy w odpowiednie podkategorie. Wybierz taką, która najbardziej pasuje do przedmiotu, o którym chcesz dyskutować.");
        else
            $("#hintCategoryType").html("Zdjęcia kategorii głównej <strong>PRZEDMIOT</strong> posegregowaliśmy w odpowiednie podkategorie. Wybierz taką, która najbardziej pasuje do przedmiotu na zdjęciu.");
    }
    else {
        if (bIsThread) {
            $("#hintCategoryType").html("Wydarzenia posegregowaliśmy w odpowiednie podkategorie. Wybierz taką, która najbardziej pasuje do rodzaju wydarzenia, o którym chcesz dyskutować.");
            $("#hintLocalization").html("<span>Uwaga!</span>po wyborze lokalizacji dyskusja zostanie automatycznie przypisane również do typu MIEJSCE.");
        }
        else {
            $("#hintCategoryType").html("Zdjęcia kategorii głównej <strong>WYDARZENIE</strong> posegregowaliśmy w odpowiednie podkategorie. Wybierz taką, która najbardziej pasuje do wydarzenia na zdjęciu.");
            $("#hintLocalization").html("<span>Uwaga!</span>po wyborze lokalizacji zdjęcie zostanie automatycznie przypisane również do typu MIEJSCE.");
        }
    }
}

var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion() {
    var version;
    var axo;
    var e;

    // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

    try {
        // version will be set for 7.X or greater players
        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
        version = axo.GetVariable("$version");
    } catch (e) {
    }

    if (!version) {
        try {
            // version will be set for 6.X players only
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

            // installed player is some revision of 6.0
            // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
            // so we have to be careful. 

            // default to the first public version
            version = "WIN 6,0,21,0";

            // throws if AllowScripAccess does not exist (introduced in 6.0r47)		
            axo.AllowScriptAccess = "always";

            // safe to call for 6.0r47 or greater
            version = axo.GetVariable("$version");

        } catch (e) {
        }
    }

    if (!version) {
        try {
            // version will be set for 4.X or 5.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
            version = axo.GetVariable("$version");
        } catch (e) {
        }
    }

    if (!version) {
        try {
            // version will be set for 3.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
            version = "WIN 3,0,18,0";
        } catch (e) {
        }
    }

    if (!version) {
        try {
            // version will be set for 2.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
            version = "WIN 2,0,0,11";
        } catch (e) {
            version = -1;
        }
    }

    return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer() {
    // NS/Opera version >= 3 check for Flash plugin in plugin array
    var flashVer = -1;

    if (navigator.plugins != null && navigator.plugins.length > 0) {
        if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
            var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
            var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
            var descArray = flashDescription.split(" ");
            var tempArrayMajor = descArray[2].split(".");
            var versionMajor = tempArrayMajor[0];
            var versionMinor = tempArrayMajor[1];
            var versionRevision = descArray[3];
            if (versionRevision == "") {
                versionRevision = descArray[4];
            }
            if (versionRevision[0] == "d") {
                versionRevision = versionRevision.substring(1);
            } else if (versionRevision[0] == "r") {
                versionRevision = versionRevision.substring(1);
                if (versionRevision.indexOf("d") > 0) {
                    versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
                }
            }
            var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
        }
    }
    // MSN/WebTV 2.6 supports Flash 4
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
    // WebTV 2.5 supports Flash 3
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
    // older WebTV supports Flash 2
    else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
    else if (isIE && isWin && !isOpera) {
        flashVer = ControlVersion();
    }
    return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) {
    versionStr = GetSwfVer();
    if (versionStr == -1) {
        return false;
    } else if (versionStr != 0) {
        if (isIE && isWin && !isOpera) {
            // Given "WIN 2,0,0,11"
            tempArray = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
            tempString = tempArray[1]; 		// "2,0,0,11"
            versionArray = tempString.split(","); // ['2', '0', '0', '11']
        } else {
            versionArray = versionStr.split(".");
        }
        var versionMajor = versionArray[0];
        var versionMinor = versionArray[1];
        var versionRevision = versionArray[2];

        // is the major.revision >= requested major.revision AND the minor version >= requested minor
        if (versionMajor > parseFloat(reqMajorVer)) {
            return true;
        } else if (versionMajor == parseFloat(reqMajorVer)) {
            if (versionMinor > parseFloat(reqMinorVer))
                return true;
            else if (versionMinor == parseFloat(reqMinorVer)) {
                if (versionRevision >= parseFloat(reqRevision))
                    return true;
            }
        }
        return false;
    }
}

function AC_AddExtension(src, ext) {
    if (src.indexOf('?') != -1)
        return src.replace(/\?/, ext + '?');
    else
        return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) {
    var str = '';
    if (isIE && isWin && !isOpera) {
        str += '<object ';
        for (var i in objAttrs)
            str += i + '="' + objAttrs[i] + '" ';
        for (var i in params)
            str += '><param name="' + i + '" value="' + params[i] + '" /> ';
        str += '></object>';
    } else {
        str += '<embed ';
        for (var i in embedAttrs)
            str += i + '="' + embedAttrs[i] + '" ';
        str += '> </embed>';
    }

    document.write(str);
}

function AC_FL_RunContent() {
    var ret =
    AC_GetArgs
    (arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
    AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType) {
    var ret = new Object();
    ret.embedAttrs = new Object();
    ret.params = new Object();
    ret.objAttrs = new Object();
    for (var i = 0; i < args.length; i = i + 2) {
        var currArg = args[i].toLowerCase();

        switch (currArg) {
            case "classid":
                break;
            case "pluginspage":
                ret.embedAttrs[args[i]] = args[i + 1];
                break;
            case "src":
            case "movie":
                args[i + 1] = AC_AddExtension(args[i + 1], ext);
                ret.embedAttrs["src"] = args[i + 1];
                ret.params[srcParamName] = args[i + 1];
                break;
            case "onafterupdate":
            case "onbeforeupdate":
            case "onblur":
            case "oncellchange":
            case "onclick":
            case "ondblClick":
            case "ondrag":
            case "ondragend":
            case "ondragenter":
            case "ondragleave":
            case "ondragover":
            case "ondrop":
            case "onfinish":
            case "onfocus":
            case "onhelp":
            case "onmousedown":
            case "onmouseup":
            case "onmouseover":
            case "onmousemove":
            case "onmouseout":
            case "onkeypress":
            case "onkeydown":
            case "onkeyup":
            case "onload":
            case "onlosecapture":
            case "onpropertychange":
            case "onreadystatechange":
            case "onrowsdelete":
            case "onrowenter":
            case "onrowexit":
            case "onrowsinserted":
            case "onstart":
            case "onscroll":
            case "onbeforeeditfocus":
            case "onactivate":
            case "onbeforedeactivate":
            case "ondeactivate":
            case "type":
            case "codebase":
                ret.objAttrs[args[i]] = args[i + 1];
                break;
            case "id":
            case "width":
            case "height":
            case "align":
            case "vspace":
            case "hspace":
            case "class":
            case "title":
            case "accesskey":
            case "name":
            case "tabindex":
                ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i + 1];
                break;
            default:
                ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i + 1];
        }
    }
    ret.objAttrs["classid"] = classid;
    if (mimeType) ret.embedAttrs["type"] = mimeType;
    return ret;
}

function detectFlash() {
    var hasReqestedVersion = DetectFlashVer(10, 0, 0);
    if (!hasReqestedVersion) {
        status.showError('Nie posiadasz najnowszej wersji flash. ');
        var flashLink = document.createElement("a");
        flashLink.setAttribute('href', "http://www.adobe.com/go/getflash/");
        flashLink.setAttribute('target', '_blank');
        flashLink.appendChild(document.createTextNode("Pobierz stąd!"));
        $("p[id$=m_pAlert]").append(flashLink);
    }
}
function uploadStarted(file) {
    var place = $("div[id*=m_upPhotosWaiting]").get(0);
    $(".progress-bar").show();

    return true;
}
function fileQueueError(file, errorcode, message) {

    switch (errorcode) {
        case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
            msg = "Pusty plik!";
            break;
        case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
            msg = "Zbyt duży rozmiar pliku! Maxymalny rozmiar to 5 MB";
            break;
        case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
            if(iUploadAvatarLimit == NaN)
                msg = "Zbyt duża liczba plików w poczekalni. Limit zdjęć to 20.";
            else
                msg = "Nie możesz dodać tylu avatarów, limit to 5.";
            break;
        default:
            msg = "Błędny plik!";
            break;
    }
    status.showError(msg);
}
function uploadError(file, errorcode, message) {
    if(errorcode != -240)   
    {
        status.showError("Wystąpił błąd podczas wgrywania pliku na serwer. Spróbuj ponownie!");
    }
    else 
    {
        PhotosAsAvatarVisibilty(false);
        status.showError("Limit 5 zdjęć został osiągnięty, musisz usunąć aby wrzucić kolejne ");  
    }
    $(".progress-bar").hide();
    setProgressValue(0);
};
function uploadSuccess(file, responseText) {
    var response = $.parseJSON(responseText);
    if (response.ok) {
        if (response.type == "avatar") {
            // avatar was added (groups avatar or profile photo)
            var Href = createElement("a", "thumb", null);
            var Img = createElement("img", "", null);
            Img.setAttribute("src", $('[id$=m_hidPath]').val()+"/" + response.path + "_micro.jpg");
            Img.setAttribute("idindb", response.id);
            Href.setAttribute("onclick", "setProfilePhoto(this)");
            Href.appendChild(Img);
            $("[id$=divAvatarHistory]").children(":last").after(Href);
            if (!($("[id$=divAvatarHistory]").is(":visible"))) {
                $("[id$=divAvatarHistory]").attr("style", "display:block");
            }

            var stats = swfu.getStats();
            iUploadAvatarLimit++;
            if(iUploadAvatarLimit == 5)
            {
                $('[id$=divSWFupload]').attr("style", "display:none");
                status.showError("Limit 5 zdjęć został osiągnięty, musisz usunąć aby wrzucić kolejne ");   
                PhotosAsAvatarVisibilty(false); 
                
            }

        }
        else {
            // photo was added
            var thumb = createThumb2(response.id, response.path + "_micro.jpg");
            if ($("div[id^=tempPhoto]:first").length > 0) {
                // there are some pictures in waiting room
                $("div[id^=tempPhoto]:first").before(thumb);
            }
            else {
                $("div[class=progress-bar]:first").next('span.no-results').remove();
                $("div[class=progress-bar]:first").after(thumb);
            }
        }

    }
    else {
        status.showError(response.status);
    }
    //swfu = new SWFUpload(wfUploadReset($('[id$=m_hidAvatarCount]').val()));
    $(".progress-bar").hide();
    setProgressValue(0);
}
function createElement(type, cssClass, val) {
    var ret = document.createElement(type);
    ret.setAttribute("class", cssClass);

    return ret;
}
function createThumb2(id, path) {
    var sDivThumbStart = "<div id='tempPhoto" + id + "' class='item wac'>";
    var sAImgStart = "<a class='thumb' id='tempPhoto" + id + "'><img src='../" + path + "' alt='foto'/></a>";
    var sDivActionsStart = "<div class='quick actions'>"
    var sSpanDescribe = "<span class='add'><a href='javascript:void(0);' onclick='return describePhoto(" + id + ");'>Opisz zdjęcie</a></span>";
    var sSpanDelete = "<span class='delete'><a href='javascript:void(0);' onclick=' return delTempPhoto.prepare(" + id + ");' id='ctl00_Main_m_ppWaitingRoom_hlDelPhoto_" + id + "' title='usuń'>usuń</a></span>";
    var sDivEnds = "</div></div>";
    var $thumb = $(sDivThumbStart + sAImgStart + sDivActionsStart + sSpanDescribe + sSpanDelete + sDivEnds);
    delTempPhoto.initFloatDialog($thumb.find('span.delete a'));
    return $thumb;
}

function uploadComplete(file) {
    this.startUpload();
}
function fileQueued(file) {
    return true;

}
function fileDialogComplete(filesSelected, filesQueued) {
    if (filesQueued > 0)
        this.startUpload();
}
function uploadProgress(file, bytesComplete, totalBytes) {
    var percent = Math.ceil((bytesComplete / file.size) * 100);
    setProgressValue(percent);
}
function setProgressValue(percent) {
    $(".count").html(percent + "%");
    $(".index").width(percent + "%");
    $(".index").html(percent);
}

// Delete Waiting Room Photo
var delTempPhoto = {
    iPhotoID: null,
    init: function(a_sPartOfIDToShowFloatDialog, a_sContainerID) {
        this.initFloatDialog($('[id*=' + a_sPartOfIDToShowFloatDialog + ']', '#' + a_sContainerID));
        return false;
    },
    initFloatDialog: function(jqoObject) {
        jqoObject.floatdialog("divDeleteTempPhoto", { closeClass: '.submit.main.closebutton.waitingroom', usebackground: false });
        return false;
    },
    prepare: function(a_iPhotoID) {
        this.iPhotoID = a_iPhotoID;
        return false;
    },
    deletePhoto: function() {
        if (this.iPhotoID != null) {
            $.ajax({
                type: "POST",
                url: $('[id$=m_hidPath]').val() + "/Photo/Actions.aspx",
                dataType: "json",
                success: onDeleteSuccess,
                error: onErrorResponse,
                data: {
                    photoid: this.iPhotoID
                }
        });
    }
    function onDeleteSuccess(response, textStatus) {
        if (response.ok) {
            $("#tempPhoto" + response.id).hide();
            $("#descPhoto" + response.id).hide();
            if ($("#TempId").val() == response.id)
                cancelSubmit();
            status.showInfo(response.status);
        }
        else {
            status.showError(response.status);
        }
    }
    return false;
},
clear: function() {
    this.iPhotoID = null;
    return false;
}
}
