
function Map() {
    var Map = {
        areaId: "",
        map:"",
        marker: false,
        marker1: false,
        marker2: false,
        geocoder: "",
        poly: false,
        polygon: false,
        image: false,
        initialized:false,
        initialize_map: function(){
            var obj = this
            var latlng = new google.maps.LatLng(37.97, 23.71);
            this.geocoder = new google.maps.Geocoder();
            var myOptions = {
                zoom: 10,
                center:latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            this.map = new google.maps.Map(document.getElementById(this.areaId), myOptions);

            //this.createImage();
            
            google.maps.event.addListener(obj.map, 'click', function(event) {
                obj.drawPoly(event);
            });
            google.maps.event.addListener(obj.map, 'rightclick', function() {
                obj.removePath();
            });

            // an yparxei marker tote fortoni ksanaei to idio marker
            if (this.marker) {
                this.marker.setMap(this.map);
                obj.geoAddressReverse(obj.marker.getPosition());
            }
        },

        clearPoly: function() {
            if (this.poly) this.poly.setMap(null);
            if (this.polygon) this.polygon.setMap(null);
            this.poly = false;
        },


        createPolyArr: function() {

        },

        createPoly: function() {
              this.clearPoly();
              var obj = this
              var polyOptions = {
                strokeOpacity: 1.0,
                strokeWeight: 3,
                geodesic: true
              }
              this.poly = new google.maps.Polyline(polyOptions);
              this.poly.setMap(this.map);
              google.maps.event.addListener(obj.poly, 'click', function() {
                    var paths = obj.poly.getPath();
                    var path = paths.getAt(0)
              });
        },
        createFinalPolygon: function() {
              var obj = this
              var polyOptions = {
                strokeOpacity: 1.0,
                strokeWeight: 3,
                geodesic: true
              }
              if (this.poly) this.poly.setMap(null);
              this.polygon = new google.maps.Polygon(polyOptions);
              var paths = obj.poly.getPath();
              var polygonPaths = obj.polygon.getPath();
              for(var i=0; i<paths.getLength(); i++) {
                    polygonPaths.push(paths.getAt(i));
              }
              this.clearPoly();
              this.polygon.setMap(this.map);
        },
        removePath: function() {
            var path = this.poly.getPath();
            path.pop();
        },
        drawPoly: function(event) {
              var path = this.poly.getPath();
              path.push(event.latLng);
        },
        createImage: function(latlng1,latlng2,image) {
            var obj = this
            if (this.marker1) this.marker1.setMap(null);
            if (this.marker2) this.marker2.setMap(null);
            
            if (latlng1 == 0) latlng1 = new google.maps.LatLng(37.95, 23.69);
            if (latlng2 == 0) latlng2 = new google.maps.LatLng(37.99, 23.73);

            
            this.resizeImage(latlng1,latlng2,image);
            // markers 1 kai 2 (marker1 kai marker2) oriothetoun tin eikona mas
            this.marker1 = new google.maps.Marker({
                    map: obj.map,
                    draggable:true,
                    position: latlng1
            });
            this.marker1.setMap(objMap.map);
            this.marker2 = new google.maps.Marker({
                    map: obj.map,
                    draggable:true,
                    position: latlng2
            });
            this.marker2.setMap(objMap.map);

            // An dragaroume ena apo ayta ta marker tote allazei to megethos tis eikonas
            google.maps.event.addListener(obj.marker1, 'dragend', function() {
                latlng1 = obj.marker1.getPosition();
                obj.resizeImage(latlng1,latlng2,image);
                updateImageBounds(latlng1.toString(),latlng2.toString()); // sozei ta ne bounds stin basi
            });
            google.maps.event.addListener(obj.marker2, 'dragend', function() {
                latlng2 = obj.marker2.getPosition();
                obj.resizeImage(latlng1,latlng2,image);
                updateImageBounds(latlng1.toString(),latlng2.toString()); // sozei ta ne bounds stin basi
            });
        },
        resizeImage: function(latlng1,latlng2,image) {
            var obj = this
            if (this.image) this.image.setMap(null);
            var imageBounds = new google.maps.LatLngBounds(latlng1,latlng2)
            this.image = new google.maps.GroundOverlay(
                "http://77.83.31.141/developing/ekloges/images/"+image,
                imageBounds);
            google.maps.event.addListener(this.image, 'click', function(event) {
                obj.drawPoly(event);
            });
            this.image.setMap(objMap.map);
            $("#hide_xartis_img").click(function() {
                if ($(this).attr("checked")) {
                    obj.image.setMap(null)
                } else {
                    obj.resizeImage(latlng1,latlng2,image);
                }
            })            
        },
        addMarker: function(latlng) {
                var obj = this;
                if (this.marker) {
                    this.marker.setMap(null);
                }
                if (latlng == undefined) latlng = this.map.getCenter();
                obj.marker = new google.maps.Marker({
                    map: obj.map,
                    draggable:true,
                    position: latlng
                });

                google.maps.event.addListener(obj.marker, 'dragend', function() {
                    obj.geoAddressReverse(obj.marker.getPosition());
                });
                obj.geoAddressReverse(latlng);

        },

        geoAddressSetenter: function (address,zoom) {
            var obj = this
            this.geocoder.geocode( { 'address': address}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    obj.map.setCenter(results[0].geometry.location);
                    obj.map.setZoom(zoom);
                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            })
        },
        geoAddress: function (address) {
            var obj = this
            this.geocoder.geocode( { 'address': address}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    obj.map.setCenter(results[0].geometry.location);
                    obj.map.setZoom(12);
                    if (obj.marker) {
                        obj.marker.setMap(null);
                    }
                    obj.addMarker(results[0].geometry.location);
                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
        },

        geoAddressReverse: function(latlng) {
            var obj = this
            this.geocoder.geocode({'latLng': latlng}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        var formatted_address = results[0].formatted_address;
                        /*
                        var formatted_address2 = results[0].formatted_address+"\n";
                        if (results[1] != undefined) formatted_address2 = formatted_address2+results[1].formatted_address+"\n";
                        if (results[2] != undefined) formatted_address2 = formatted_address2+results[2].formatted_address+"\n";
                        if (results[3] != undefined) formatted_address2 = formatted_address2+results[3].formatted_address+"\n";
                        if (results[4] != undefined) formatted_address2 = formatted_address2+results[4].formatted_address+"\n";
                        if (results[5] != undefined) formatted_address2 = formatted_address2+results[5].formatted_address+"\n";
                        if (results[6] != undefined) formatted_address2 = formatted_address2+results[6].formatted_address+"\n";
                        if (results[7] != undefined) formatted_address2 = formatted_address2+results[7].formatted_address+"\n";
                        alert(formatted_address2);
                        */
                        $("#aggelies_address").val(formatted_address);
                    }
                } else {
                    alert("Geocoder failed due to: " + status);
                }
            });
        }
    }
    return Map;
}
//Κάνει show το Pop Up
function Tip(content) {
    $("#popupcontent").hide();
    $("#popupcontent").html("");
    $("#popupcontent").append(content);
    $("#popupbackground").fadeTo("fast", 0.4, function() {
        $("#popuptipper").fadeIn("fast");
        $("#popupcontent").fadeIn("fast");
    });
    UnTip();
}

function Tip2(content) {
    $("#popupcontent2").hide();
    $("#popupcontent2").html("");
    $("#popupcontent2").append(content);
    $("#popupcontent2").fadeIn("fast");
    UnTip2();
}

//Κάνει hide το Pop Up
function UnTip() {
    $("#untip").click(function() {
        $("#popupcontent").css("background","#ffffff");
        $("#popupcontent").fadeOut("fast",function() {
            $("#popupcontent").html('');
        })
        $("#popupbackground").fadeTo("fast", 0, function() {
            $("#popupbackground").fadeOut("fast");
            $("#popuptipper").fadeOut("fast");
            $("#tipcontent").attr("class","");
        });
    })
}

function UnTip2() {
    $("#untip2").click(function() {
        $("#popupcontent2").fadeOut("fast", function() {
            $("#popupcontent2").html("");
        });
    })
}

// ejagei tou epilegmeno query (querystring) apo to link pou eimaste

function querySt(ji) {
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji) {
			return ft[1];
		}
	}
}

function isPhoneNumber(str) {
    var rePhoneNumber = new RegExp(/^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/);
    if (!rePhoneNumber.test(str)) {
        return true;
    }
    return true;
}

function emailcheck(str) {
	var at = "@"
	var dot = "."
	var lat = str.indexOf(at)
	var lstr = str.length
	var ldot = str.indexOf(dot)
	if (str.indexOf(at) == -1) {
		return false
	}
	if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
		return false
	}
	if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
		return false
	}

        if (str.indexOf(at, (lat + 1)) != -1) {
		return false
	}

	if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
		return false
	}

	if (str.indexOf(dot, (lat + 2)) == -1) {
		return false
	}

	if (str.indexOf(" ") != -1) {
		return false
	}
	return true
}

jQuery.fn.tabber = function(options) {
    var defaults = {
        tabs: { name: '.tabs' },
        panels: {
            name:      '.tabpanel',
            container: '.tabpanels'
        }
    };
    var opts = jQuery.extend(true, defaults, options);
    var panels = this.find(opts.panels.name);
    
    this.find(opts.tabs.name+' a').click(function(evt) {
        evt.preventDefault();
        var $tis = $(this);
        var panelName = $tis.attr('href').substr(1);
        panels.hide();
        panels.filter(function(index) {
            return $('a[name='+panelName+']', this).length == 1;
        }).each(function() {
            
            var $tis = $(this);
            $tis.show();
            if (opts.panels.cssClass) {
                $tis.addClass(opts.panels.cssClass);
            }
            if (opts.panels.style) {
                if ($tis.is(':first-child')) {
                    $tis.parent(opts.panels.container).attr('style', opts.panels.styleRestore);
                } else {
                    $tis.parent(opts.panels.container).attr('style', opts.panels.style);
                }
            }
        });
        $tis.parent('li').siblings().removeClass('selected');
        $tis.parent('li').addClass('selected');
    });
};
function getElementId(obj) {
    var attrId = $(obj).attr("id");
    var attrIdArr = attrId.split("_");
    return attrIdArr[1];
}

function isInteger(s) {
  return (s.toString().search(/^-?[0-9]+$/) == 0);
}

function implode (glue, pieces) {
    // Joins array elements placing glue string between items and return one string
    //
    // version: 1006.1915
    // discuss at: http://phpjs.org/functions/implode    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Waldo Malqui Silva
    // +   improved by: Itsacon (http://www.itsacon.net/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: implode(' ', {first:'Kevin', last: 'van Zonneveld'});
    // *     returns 2: 'Kevin van Zonneveld'
    var i = '', retVal='', tGlue='';
    if (arguments.length === 1) {
        pieces = glue;
        glue = '';
    }
    if (typeof(pieces) === 'object') {
        if (pieces instanceof Array) {
            return pieces.join(glue);
        }
        else {
            for (i in pieces) {
                retVal += tGlue + pieces[i];
                tGlue = glue;
            }
            return retVal;
        }
    }
    else {
        return pieces;
    }
}
function getElementId(obj) {
    var attrId = $(obj).attr("id");
    var attrIdArr = attrId.split("_");
    return attrIdArr[1];
}
//kanei escape kai afairei ton leyko xori se ena string
function fixPostedData(str) {
    return escape(trim(str));
}

function isEmpty(str) {
    if ( null == str || "" == str ) {
        return true;
    }
    return false;
}

function trim(str, chars) {
        if (isEmpty(str)) str = "";
	return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


var perioxi_id;
function nomoiEvent() {
    $("#periferia_id").change(function() {
        if (candicate != undefined) candicate.periferia_id = $(this).val();
        perioxi_id = $(this).val();
        var data = {action:"getnomoi",periferia_id:$(this).val()}
        $.post("ajax/candicate.php", data, function(result){
            $("#nomoi_drp_area").html(result);
            dimoiEvent();
        })
    })
}
function dimoiEvent() {
    $("#nomos_id").change(function() {
        var data = {action:"getdimoi",nomos_id:$(this).val()}
        $.post("ajax/candicate.php", data, function(result){
            $("#dimoi_drp_area").html(result);
            $("#dimos_id").change(function() {
                candicate.dimos_id = $(this).val();
                perioxi_id = $(this).val();
                getSyndiasmous(candicate.dimos_id,2,candicate.electionid); // ajax pou epistrefei tous syndiasmous tou dimou
                addNewSyndiasmousForm(candicate.dimos_id,2,candicate.electionid); // event gia tin eisagogi neo nomou
            })
        })
    })
}
