/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/

(function($) { $.fn.hoverIntent = function(f, g) { var cfg = { sensitivity: 7, interval: 100, timeout: 0 }; cfg = $.extend(cfg, g ? { over: f, out: g} : f); var cX, cY, pX, pY; var track = function(ev) { cX = ev.pageX; cY = ev.pageY; }; var compare = function(ev, ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); if ((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) { $(ob).unbind("mousemove", track); ob.hoverIntent_s = 1; return cfg.over.apply(ob, [ev]); } else { pX = cX; pY = cY; ob.hoverIntent_t = setTimeout(function() { compare(ev, ob); }, cfg.interval); } }; var delay = function(ev, ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); ob.hoverIntent_s = 0; return cfg.out.apply(ob, [ev]); }; var handleHover = function(e) { var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget; while (p && p != this) { try { p = p.parentNode; } catch (e) { p = this; } } if (p == this) { return false; } var ev = jQuery.extend({}, e); var ob = this; if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); } if (e.type == "mouseover") { pX = ev.pageX; pY = ev.pageY; $(ob).bind("mousemove", track); if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout(function() { compare(ev, ob); }, cfg.interval); } } else { $(ob).unbind("mousemove", track); if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout(function() { delay(ev, ob); }, cfg.timeout); } } }; return this.mouseover(handleHover).mouseout(handleHover); }; })(jQuery);


/******************************************************************/
/* Replace static google map with dynamic map through client side */
/******************************************************************/

function trackEnquiry(action) {
    var pageTracker = _gat._getTracker("UA-247980-10");
    pageTracker._initData();
    pageTracker._trackPageview();
    pageTracker._trackEvent('Enquiry', action);

}

$(document).ready(function() {
    if ($('#pageMode') && $('#pageMode').val() == 'edit') return;
	if ($('#pageMode') && $('#pageMode').val() == 'preview') return;

    var staticMaps = $('.gmap');

    var parseQueryString = function(src) {
        var qs = new Hashtable();
        $.each(src.split('&'), function(i) {
            var kv = this;
            if (kv == "") return;
            var key = kv.split('=')[0];
            var value = kv.split('=')[1];
            qs.put(key, value);
        });
        return qs;
    };

    $.each(staticMaps, function(i) {
        var staticMap = this;

        //grab all meta
        var src = $(staticMap).attr('src').replace(/^.*\?/, '');
        var queryString = parseQueryString(src);
        var lat = queryString.get('center').split(',')[0];
        var lng = queryString.get('center').split(',')[1];
        var width = queryString.get('size').split('x')[0];
        var height = queryString.get('size').split('x')[1];
        var zoom = Number(queryString.get('zoom'));
        var maptype = queryString.get('maptype');
        var markers = queryString.get('markers');


        //insert placeholder
        var dynamicMap = $('<div/>').attr('id', 'dynamic_gmap_' + i)
            .css('display', 'inline-block')
            .css('width', width + 'px')
            .css('height', height + 'px')
            .css('overflow', 'hidden');
        $(staticMap).after(dynamicMap);
        $(staticMap).hide();

        //create gmap object
        var tmpGMap = new GMap2(dynamicMap[0]);
        tmpGMap.setCenter(new GLatLng(lat, lng), zoom);
        tmpGMap.setUIToDefault();

        if (maptype == 'roadmap') tmpGMap.setMapType(G_NORMAL_MAP);
        else if (maptype == 'satellite') tmpGMap.setMapType(G_SATELLITE_MAP);
        else if (maptype == 'hybrid') tmpGMap.setMapType(G_HYBRID_MAP);
        else if (maptype == 'terrain') tmpGMap.setMapType(G_PHYSICAL_MAP);

        markers = markers.replace(/%7C/g, '|');

        $.each(markers.split('|'), function(i) {
            if (this == "") return;
            var mlat = this.split(',')[0];
            var mlng = this.split(',')[1];
            tmpGMap.addOverlay(new GMarker(new GLatLng(mlat, mlng)));
        });

    });
});

/******************************************************************/
/* Client side code for email subscription component              */
/******************************************************************/
var EmailSC_frontEnd = {
    subscribe: function(cid, dbId) {
        var t = this;
        var fieldArray = []; //we will fill this and send to web service
        var valid = true;

        // text fields
        var textFields = $('.componentES_' + cid + ' .fields input.text');
        $.each(textFields, function(i) {
            var field = this;
            var type = field.type.toLowerCase(); var name = field.name; var value = field.value; var checked = field.checked;

            if ($(field).hasClass('mandatory') && $.trim(value).length <= 0) { valid = false; return false; } //validation
            fieldArray.push({ Name: name, Value: value });

        });

        // radio fields
        var radioWraps = $('.componentES_' + cid + ' .fields .radio_wrap');
        $.each(radioWraps, function(i) {
            var name = $(this).attr('title');
            var mandatory = $(this).hasClass('mandatory');
            var $radios = $('.radio:checked', $(this));
            if (mandatory && $radios.length <= 0) { valid = false; return false; } //validation
            var value = $radios.val();
            fieldArray.push({ Name: name, Value: value });
        });


        // select fields
        var selectFields = $('.componentES_' + cid + ' .fields select.field');
        $.each(selectFields, function(i) {
            var field = this;
            var name = field.name;
            var options = $('option', $(field));
            var value = null;

            $.each(options, function(j) {
                var option = this;
                if (option.selected && $(field).hasClass('mandatory') && $(option).hasClass('default')) { //validation
                    valid = false;
                    return false;
                }
                if (option.selected) {
                    value = option.value;
                    return false;
                }
            });

            if (value != null) fieldArray.push({ Name: name, Value: value });
        });

        // checkbox field
        var checkboxWraps = $('.componentES_' + cid + ' .fields .checkbox_wrap');
        $.each(checkboxWraps, function(i) {
            var name = $(this).attr('title');
            var mandatory = $(this).hasClass('mandatory');
            var $checkboxes = $('.checkbox:checked', $(this));
            var values = '';

            $.each($checkboxes, function(j) {
                values += values.length > 0 ? ', ' : '';
                values += $(this).val();
            });

            if (mandatory && values.length <= 0) { valid = false; return false; } //validation
            fieldArray.push({ Name: name, Value: values });
        });

        // date field
        var dateFields = $('.componentES_' + cid + ' .fields .date');
        $.each(dateFields, function(i) {
            var name = $(this).attr('name');
            var value = $(this).val();
            var mandatory = $(this).hasClass('mandatory');
            if (mandatory && $.trim(value).length <= 0) { valid = false; return false; }
            fieldArray.push({ Name: name, Value: value });
        });

        // stop here if form is invalid
        if (!valid) {
            $('.componentES_' + cid + ' .mandatory_error').show();
            $('.svcError_' + cid).html('Fields marked with asterisks (*) are mandatory');
            return;
        } else {
            $('.componentES_' + cid + ' .mandatory_error').hide();
            $('.svcError_' + cid).html('');
        }

        // turn on ajax loader image
        $('.componentES_' + cid + ' .loader').show();

        //send via service -- (servicePath, methodName, useGet, params, onSuccess, onFailure, userContext, timeout)
        Sys.Net.WebServiceProxy.invoke('/awms/services/EmailSubscription.asmx', 'subscribeContact', false, { databaseId: dbId, customFields: fieldArray },
        function(resp) {
            $('.svcSuccess_' + cid).html('Subscription success');
            $('.componentES_' + cid + ' .loader').hide();
        }, function(err) {
            //$('.svcError_' + cid).html(err.get_message() + '<br/>' + err.get_exceptionType() + '<br/><pre>' + err.get_stackTrace() + '</pre>');
            $('.svcError_' + cid).html(err.get_message());
            $('.componentES_' + cid + ' .loader').hide();
        });
    },

    // Initialize component on load / update
    init: function(cid) {
        $.each($('.componentES_' + cid + ' .date'), function(i) {
            $(this).datepicker({ dateFormat: 'yy-mm-dd', changeYear: true });
        });
    }
};
