﻿var EmptyImageUrl = 'http://davidgriffin.com/listingimages/PropImage.gif';

var isMapCompatible = false;
var iconGriffin;
var iconMLS;

var hashPrevValues = new Object();
var hashMaps = new Object();
var hashPropertyStates = new Object();      // 1 - image, 2 - info, 3 - map.

Array.prototype.clear = function() {
    this.length = 0;
}

Array.prototype.has = function(v, i) {
    for (var j = 0; j < this.length; j++) {
        if (this[j] == v) return (!i ? true : j);
    }
    return false;
}

Array.prototype.indexOf = function(v) {
    for (var j = 0; j < this.length; j++) {
        if (this[j] == v) return j;
    }
    return -1;
}

Array.prototype.removeAt = function(iIndex) {
    var vItem = this[iIndex];
    if (vItem) {
        this.splice(iIndex, 1);
    }
    return vItem;
};

function ID(id) { return document.getElementById(id); }

function GetControlValue(obj) {
    if (!obj) return '';

    if (obj.tagName.toUpperCase() == 'INPUT') {
        if (obj.type == 'text')
            return obj.value;

        if (obj.type == 'radio') {
            var pos = obj.id.lastIndexOf('_');
            var radioIndex = obj.id.substr(pos + 1);

            if (obj.checked) {
                return radioIndex;
            }
            else {
                var idPart = obj.id.substr(0, pos + 1);
                var i = 0;
                while (1 == 1) {
                    var elem = window.document.getElementById(idPart + i);
                    if (elem) {
                        if (elem.checked)
                            return i;
                    }
                    else
                        break;

                    i++;
                }
            }
        }

        if (obj.type == 'checkbox') {
            var selIndexes = '';

            var pos = obj.id.lastIndexOf('_');
            var idPart = obj.id.substr(0, pos + 1);
            var i = 0;
            while (1 == 1) {
                var elem = ID(idPart + i);
                if (elem) {
                    if (elem.checked)
                        selIndexes += (selIndexes == '' ? '' : ',') + i;
                }
                else
                    break;

                i++;
            }

            return selIndexes;
        }
    }

    if (obj.tagName.toUpperCase() == 'SELECT') {
        return obj.options[obj.selectedIndex].value;
    }

    if (obj.tagName.toUpperCase() == 'TEXTAREA') return obj.value;

    return '';
}

function GetPropertyValue(name) {
    var form = window.document.forms[0];
    var hiddenFields = form.getElementsByTagName('input');

    for (var i = 0; i < hiddenFields.length; i++) {
        if (hiddenFields[i].type == 'hidden') {
            if (hiddenFields[i].name.indexOf(name) >= 0)
                return hiddenFields[i].value;
        }
    }

    return '';
}

function SetPropertyValue(name, val) {
    var form = window.document.forms[0];
    var hiddenFields = form.getElementsByTagName('input');

    for (var i = 0; i < hiddenFields.length; i++) {
        if (hiddenFields[i].type == 'hidden') {
            if (hiddenFields[i].name.indexOf(name) >= 0)
                hiddenFields[i].value = val;
        }
    }
}

function OnPageInit() {
    hashPrevValues['STypes'] = GetControlValue(ID(GetPropertyValue('STypesClientId')));

    if(GetPropertyValue('Page') == 'MobileDetail')
        InitGMaps();
}

function GetOptions(obj) {
    var hash = new Object();

    for (var i = 0; i < obj.options.length; i++)
        hash[obj.options[i].value] = obj.options[i].text

    return hash;
}

function OnChangeSTypes() {
    var clientId = GetPropertyValue('STypesClientId');
    if (!clientId) return;

    var elem = ID(clientId);
    if (!elem) return;

    var cbxPrice1 = $("#" + GetPropertyValue('SPrices1ClientId'));
    var cbxPrice2 = $("#" + GetPropertyValue('SPrices2ClientId'));
    if (!cbxPrice1 || !cbxPrice2) return;

    var selVal = GetControlValue(elem);
    if (selVal == 'Lease' || hashPrevValues['STypes'] == 'Lease') {
        cbxPrice1.removeOption(/./);
        cbxPrice2.removeOption(/./);

        cbxPrice1.addOption(GetOptions(ID(GetPropertyValue('HelperPrice1' + (selVal == 'Lease' ? 'Lease' : '') + 'ClientId'))), false);
        cbxPrice2.addOption(GetOptions(ID(GetPropertyValue('HelperPrice2' + (selVal == 'Lease' ? 'Lease' : '') + 'ClientId'))), false);
    }

    hashPrevValues['STypes'] = selVal;
}

function InitIcons() {
    iconGriffin = new GIcon();
    iconGriffin.image = "http://davidgriffin.com/images/dgGoogleIcon.png";
    iconGriffin.shadow = "http://www.google.com/mapfiles/shadow50.png";
    iconGriffin.iconSize = new GSize(35, 35);
    iconGriffin.shadowSize = new GSize(22, 20);
    iconGriffin.iconAnchor = new GPoint(6, 20);
    iconGriffin.infoWindowAnchor = new GPoint(5, 1);

    iconMLS = new GIcon();
    iconMLS.image = "http://davidgriffin.com/images/mlsGoogleIcon.png";
    iconMLS.shadow = "http://www.google.com/mapfiles/shadow50.png";
    iconMLS.iconSize = new GSize(35, 35);
    iconMLS.shadowSize = new GSize(22, 20);
    iconMLS.iconAnchor = new GPoint(6, 20);
    iconMLS.infoWindowAnchor = new GPoint(5, 1);
}

function InitGMaps() {
    isMapCompatible = GBrowserIsCompatible();
    if (!isMapCompatible) return;

    InitIcons();
}

function OnPropertyImageLoad(listingId) {
    $("#pnlF_" + listingId).hide();

    if (ID("imgI_" + listingId))
        if (ID("imgI_" + listingId).src == EmptyImageUrl)
        HandleWrongImage(listingId, true);
}

function OnImageLoaderClick(listingId) {
    $("#pnlF_" + listingId).hide();
}

function GetValueOfProperty(ary, listingId) {
    var retVal = '';
    for(var i = 0; i < ary.length; i++) {
        var ary2 = ary[i].split('=');
        if (ary2.length == 2) {
            if (ary2[0] == listingId) {
                retVal = ID(ary2[1]).value;
                break;
            }
        }
    }

    return retVal;
}

function GetElemOfProperty(ary, listingId) {
    var retVal = '';
    for (var i = 0; i < ary.length; i++) {
        var ary2 = ary[i].split('=');
        if (ary2.length == 2) {
            if (ary2[0] == listingId) {
                return ID(ary2[1]);
                break;
            }
        }
    }

    return retVal;
}

function CheckInitialState(listingId) {
    if (hashPropertyStates[listingId] == undefined || hashPropertyStates[listingId] == null)
        hashPropertyStates[listingId] = 1;
}

function OnClickChangeImage(listingId, plus) {
    var imgElem = $("#imgI_" + listingId);
    if (!imgElem) return;

    var pnlElem = $("#pnlI_" + listingId);
    if (!pnlElem) return;

    var pnlMap = $("#pnlM_" + listingId);
    if (!pnlMap) return;

    var pnlFade = $("#pnlF_" + listingId);
    if (!pnlFade) return;

    CheckInitialState(listingId);

    // Get images.
    var val;
    val = GetValueOfProperty(GetPropertyValue('ImagesIds').split(';'), listingId);
    var aryImages = val.split(',');

    // Get Griffin State.
    val = GetValueOfProperty(GetPropertyValue('IsGriffinIds').split(';'), listingId);
    var isGriffin = parseInt(val);

    // Get geocodes.
    coord1 = 0;
    coord2 = 0;

    val = GetValueOfProperty(GetPropertyValue('Coord1Ids').split(';'), listingId);
    if (val != '' && val != '0')
        coord1 = parseFloat(val.replace(',', '.'));

    val = GetValueOfProperty(GetPropertyValue('Coord2Ids').split(';'), listingId);
    if (val != '' && val != '0')
        coord2 = parseFloat(val.replace(',', '.'));

    var bHasMap = isMapCompatible && (coord1 != 0 || coord2 != 0);
    var bHasImages = aryImages.length > 0 ? true : false;

    var curState = hashPropertyStates[listingId];
    var newPos;

    // Currently is info panel.
    if (curState == 2) {
        if (plus > 0) {
            if (bHasMap)
                newPos = -2;
            else {
                if (!bHasImages) return;
                newPos = plus > 0 ? 0 : aryImages.length - 1;
            }
        }
        else {
            if (bHasImages)
                newPos = plus > 0 ? 0 : aryImages.length - 1;
            else {
                if (!bHasMap) return;
                newPos = -2;
            }
        }
    }
    else {
        // Currently is map.
        if (curState == 3) {
            if (plus > 0) {
                if (bHasImages)
                    newPos = plus > 0 ? 0 : aryImages.length - 1;
                else {
                    newPos = -1;
                }
            }
            else {
                newPos = -1;
            }
        }
        // Currently is an image.
        else {
            var newPos = aryImages.indexOf(imgElem.attr('src')) + plus;
            if (newPos >= aryImages.length)
                newPos = -1;
            else {
                if (newPos < 0) {
                    if (bHasMap)
                        newPos = -2;
                    else
                        newPos = -1;
                }
            }
        }
    }

    if (newPos == -1) {
        // Show Info.
        pnlFade.hide();
        imgElem.hide();
        if (pnlMap) pnlMap.hide();
        pnlElem.show();
        hashPropertyStates[listingId] = 2;
    }
    else if (newPos == -2) {
        // Show Map.
        pnlFade.hide();
        imgElem.hide();
        pnlElem.hide();
        if (pnlMap) pnlMap.show();
        InitSmallMap(listingId, coord1, coord2, isGriffin);
        hashPropertyStates[listingId] = 3;
    }
    else {
        // Show Images.
        if (pnlMap) pnlMap.hide();
        pnlElem.hide();
        pnlFade.show();
        imgElem.show();
        imgElem.attr('src', aryImages[newPos]);
        ImgLoad(listingId, plus, aryImages[newPos]);
        hashPropertyStates[listingId] = 1;
    }
}

function ImgLoad(listingId, plus, src) {
    var imgElem = $("#imgI_" + listingId);
    if (!imgElem) return;

    var pnlElem = $("#pnlI_" + listingId);
    if (!pnlElem) return;

    var pnlMap = $("#pnlM_" + listingId);
    if (!pnlMap) return;

    var pnlFade = $("#pnlF_" + listingId);
    if (!pnlFade) return;

    CheckInitialState(listingId);

    // Get images.
    var val;
    val = GetValueOfProperty(GetPropertyValue('ImagesIds').split(';'), listingId);
    var aryImages = val.split(',');

    // Get Griffin State.
    val = GetValueOfProperty(GetPropertyValue('IsGriffinIds').split(';'), listingId);
    var isGriffin = parseInt(val);

    // Get geocodes.
    coord1 = 0;
    coord2 = 0;

    val = GetValueOfProperty(GetPropertyValue('Coord1Ids').split(';'), listingId);
    if (val != '' && val != '0')
        coord1 = parseFloat(val.replace(',', '.'));

    val = GetValueOfProperty(GetPropertyValue('Coord2Ids').split(';'), listingId);
    if (val != '' && val != '0')
        coord2 = parseFloat(val.replace(',', '.'));

    var bHasMap = isMapCompatible && (coord1 != 0 || coord2 != 0);
    var bHasImages = aryImages.length > 0 ? true : false;

    var curState = hashPropertyStates[listingId];

    var oImg = new Image;
    oImg.onload = function() {
        imgElem.attr('src', src);
    }

    oImg.onerror = function() {
        var newPos = aryImages.indexOf(src) + plus;
        if (newPos >= aryImages.length)
            newPos = -1;
        else {
            if (newPos < 0) {
                if (bHasImages)
                    newPos = -2;
                else
                    newPos = -1;
            }
        }

        if (newPos == -1) {
            // Show Info.
            pnlFade.hide();
            imgElem.hide();
            if (pnlMap) pnlMap.hide();
            pnlElem.show();
            hashPropertyStates[listingId] = 2;
        }
        else if (newPos == -2) {
            // Show Map.
            pnlFade.hide();
            imgElem.hide();
            pnlElem.hide();
            if (pnlMap) pnlMap.show();
            InitSmallMap(listingId, coord1, coord2, isGriffin);
            hashPropertyStates[listingId] = 3;
        }
        else {
            // Show Images.
            if (pnlMap) pnlMap.hide();
            pnlElem.hide();
            pnlFade.show();
            imgElem.show();

            newScr = aryImages[newPos];
            if (aryImages.indexOf(src) >= 0) {
                aryImages.removeAt(aryImages.indexOf(src));

                var imgs = GetElemOfProperty(GetPropertyValue('ImagesIds').split(';'), listingId);
                imgs.value = (imgs.value + ',').replace(src + ',', '');
                if (imgs.value.substring(imgs.value.length - 1, imgs.value.length) == ',')
                    imgs.value = imgs.value.substring(0, imgs.value.length - 1);
            }
            ImgLoad(listingId, plus, newScr);

            hashPropertyStates[listingId] = 1;
        }
    }

    oImg.src = src;
}

function OnErrorPropertyImageLoad(listingId) {
    HandleWrongImage(listingId, false);
}

function HandleWrongImage(listingId, bSuccess) {
    var pnlFade = $("#pnlF_" + listingId);
    if (!pnlFade) return;

    var imgElem = $("#imgI_" + listingId);
    if (!imgElem) return;

    var pnlElem = $("#pnlI_" + listingId);
    if (!pnlElem) return;

    var pnlMap = $("#pnlM_" + listingId);
    if (!pnlMap) return;

    // Get images.
    var val;
    val = GetValueOfProperty(GetPropertyValue('ImagesIds').split(';'), listingId);
    var aryImages = val.split(',');

    // Get Griffin State.
    val = GetValueOfProperty(GetPropertyValue('IsGriffinIds').split(';'), listingId);
    var isGriffin = parseInt(val);

    // Get geocodes.
    coord1 = 0;
    coord2 = 0;

    val = GetValueOfProperty(GetPropertyValue('Coord1Ids').split(';'), listingId);
    if (val != '' && val != '0')
        coord1 = parseFloat(val.replace(',', '.'));

    val = GetValueOfProperty(GetPropertyValue('Coord2Ids').split(';'), listingId);
    if (val != '' && val != '0')
        coord2 = parseFloat(val.replace(',', '.'));

    var bHasMap = isMapCompatible && (coord1 != 0 || coord2 != 0);
    var bHasImages = aryImages.length > 0 ? true : false;

    if (bHasMap) {
        pnlFade.hide();
        pnlMap.show();
        InitSmallMap(listingId, coord1, coord2, isGriffin);
        imgElem.hide();

        hashPropertyStates[listingId] = 3;
    }
    else {
        pnlFade.hide();
        pnlMap.hide();
        pnlElem.show();
        imgElem.hide();

        hashPropertyStates[listingId] = 2;
    }
}

function hasInHashMaps(listingId) {
    for (var item in hashMaps)
        if (item == listingId) return true;

    return false;
}

function InitSmallMap(listingId, coord1, coord2, isGriffin) {
    var pnlMap = ID("pnlM_" + listingId);
    if (!pnlMap) return;

    if (hasInHashMaps(listingId)) return;

    var propCoord = new GLatLng(coord2, coord1);

    var smallMap = new GMap2(pnlMap);
    smallMap.addControl(new GSmallMapControl());
    smallMap.addControl(new GMapTypeControl());
    smallMap.setCenter(propCoord, 16);

    var newOverlay = new GMarker(propCoord, isGriffin ? iconGriffin : iconMLS);
    smallMap.addOverlay(newOverlay);

    hashMaps[listingId] = smallMap;
}
