/**
* hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
* <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(at)cherne(dot)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 ev = jQuery.extend({}, e); var ob = this; if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t) } if (e.type == "mouseenter") { 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.bind('mouseenter', handleHover).bind('mouseleave', handleHover) } })(jQuery);

/*custom fade in*/
$.fn.customFadeIn = function (speed, callback) {
    $(this).fadeIn(speed, function () {
        if (jQuery.browser.msie) {
            $(this).get(0).style.removeAttribute('filter');
        }
        if (callback != undefined) {
            callback();
        }
    });
};

/*Proxy getJSON implemented by Dion*/
$.extend({
    getProxyJSON: function (url, callback) {
        
        return $.ajax({
            type: "GET",
            url: "/proxy/Request.aspx?url=" + encodeURIComponent(url),
            processData: true,
            data: {},
            dataType: "json",
            success: function (json) {
                callback(json);
            },
            error: function (x, y, z) {
                // x.responseText should have what's wrong
                //alert("Error: " + x.responseText);                
            }
        });
    }
});

/*tiny sort*/
(function (b) { b.tinysort = { id: "TinySort", version: "1.0.4", defaults: { order: "asc", attr: "", place: "start", returns: false} }; b.fn.extend({ tinysort: function (h, j) { if (h && typeof (h) != "string") { j = h; h = null } var e = b.extend({}, b.tinysort.defaults, j); var p = {}; this.each(function (t) { var v = (!h || h == "") ? b(this) : b(this).find(h); var u = e.order == "rand" ? "" + Math.random() : (e.attr == "" ? v.text() : v.attr(e.attr)); var s = b(this).parent(); if (!p[s]) { p[s] = { s: [], n: []} } if (v.length > 0) { p[s].s.push({ s: u, e: b(this), n: t }) } else { p[s].n.push({ e: b(this), n: t }) } }); for (var g in p) { var d = p[g]; d.s.sort(function k(t, s) { var i = t.s.toLowerCase ? t.s.toLowerCase() : t.s; var u = s.s.toLowerCase ? s.s.toLowerCase() : s.s; if (c(t.s) && c(s.s)) { i = parseFloat(t.s); u = parseFloat(s.s) } return (e.order == "asc" ? 1 : -1) * (i < u ? -1 : (i > u ? 1 : 0)) }) } var m = []; for (var g in p) { var d = p[g]; var n = []; var f = b(this).length; switch (e.place) { case "first": b.each(d.s, function (s, t) { f = Math.min(f, t.n) }); break; case "org": b.each(d.s, function (s, t) { n.push(t.n) }); break; case "end": f = d.n.length; break; default: f = 0 } var q = [0, 0]; for (var l = 0; l < b(this).length; l++) { var o = l >= f && l < f + d.s.length; if (a(n, l)) { o = true } var r = (o ? d.s : d.n)[q[o ? 0 : 1]].e; r.parent().append(r); if (o || !e.returns) { m.push(r.get(0)) } q[o ? 0 : 1]++ } } return this.pushStack(m) } }); function c(e) { var d = /^\s*?[\+-]?(\d*\.?\d*?)\s*?$/.exec(e); return d && d.length > 0 ? d[1] : false } function a(e, f) { var d = false; b.each(e, function (h, g) { if (!d) { d = g == f } }); return d } b.fn.TinySort = b.fn.Tinysort = b.fn.tsort = b.fn.tinysort })(jQuery);

/******************************************************************/
/* Replace static google map with dynamic map through client side */
/******************************************************************/
$(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 });
        });
    }
};

/******************************************************************/
/* Form Validation                                                */
/******************************************************************/
function ValidateAndSubmit(evt, validationGroup) {
    // Ascend from the button that triggered this click event 
    //  until we find a container element flagged with 
    //  .validationGroup and store a reference to that element.
    var $group = $(evt.currentTarget).parents(validationGroup);

    var isValid = true;

    // Descending from that .validationGroup element, find any input
    //  elements within it, iterate over them, and run validation on 
    //  each of them.
    $group.find('.validate').each(function (i, item) {
        if (!$(item).valid())
            isValid = false;
    });

    // If any fields failed validation, prevent the button's click 
    //  event from triggering form submission.
    if (!isValid)
        evt.preventDefault();
}


/******************************************************************/
/* UI script                                                      */
/******************************************************************/
$(document).ready(function () {

    /******************************************************************/
    /* Footer Newsletter                                              */
    /******************************************************************/
    var swapValues = [];
    $(".watermarks").each(function (i) { swapValues[i] = $(this).val(); $(this).focus(function () { if ($(this).val() == swapValues[i]) { $(this).val("") } }).blur(function () { if ($.trim($(this).val()) == "") { $(this).val(swapValues[i]) } }) });

    /******************************************************************/
    /* Homepage - Solution Cycle                                      */
    /******************************************************************/
    var $solutionCycle;
    if ($('#solutionsHolder').length > 0) {
        $solutionCycle = $('#solutionsHolder').cycle({
            fx: 'scrollHorz',
            slideExpr: '.solution',
            next: '#nextSolution',
            prev: '#prevSolution',
            pagerEvent: 'mouseover',
            timeout: 0,
            speed: 1500,
            cleartype: true,
            onPagerEvent: function (slideIndex, slideElement) {
                $('.chart img').animate({ 'top': '25px' }, { queue: false }, "500");
                $('.chart .graph').animate({ 'top': '11px' }, { queue: false }, "500");
                $($('.chart').get(slideIndex)).find(".graph").animate({ 'top': '1px' }, { queue: false }, "1000");
                $($('.chart').get(slideIndex)).find("img").animate({ 'top': '14px' }, { queue: false }, "1000");
            },
            onPrevNextEvent: function (isNext, slideIndex, slideElement) {
                $('.chart img').animate({ 'top': '25px' }, { queue: false }, "500");
                $('.chart .graph').animate({ 'top': '11px' }, { queue: false }, "500");
                $($('.chart').get(slideIndex)).find(".graph").animate({ 'top': '1px' }, { queue: false }, "1000");
                $($('.chart').get(slideIndex)).find("img").animate({ 'top': '14px' }, { queue: false }, "1000");
            },
            pager: '#solutionsPager',
            pagerAnchorBuilder: function (index, slide) {
                var slideId = slide.id.replace("Solution", "");
                var slideTitle = "";
                switch (slideId) {
                    case "strategy":
                        slideTitle = "Adrenalin Media Digital Strategy Sydney";
                        break;
                    case "design":
                        slideTitle = "Adrenalin Media Web Design Sydney";
                        break;
                    case "technology":
                        slideTitle = "Adrenalin Media Web Development Sydney";
                        break;
                };
                return '<div id="' + slideId + 'Chart" class="chart" title="' + slideTitle + '"><div class="graph"></div><div class="mask"></div><img src="images/title' + slideId + '.png" alt="' + slideTitle + '" /></div>';
            }
        }); //cycle    
    }

    /******************************************************************/
    /* Form              			  */
    /******************************************************************/
    $(".form .text input, .form .textarea textarea").each(function () {
        var labelCaption = $(this).parents('.instanceHolder').find('.caption');
        if ($(this).val().length > 0) { $(labelCaption).addClass("editing"); }
        else { $(labelCaption).removeClass("editing"); }
    });

    $(".form .text input, .form .textarea textarea")
        .bind("focus", function () {
            var labelCaption = $(this).parents('.instanceHolder').find('.caption');
            $(labelCaption).addClass("editing");
        })
        .bind("blur", function () {
            var labelCaption = $(this).parents('.instanceHolder').find('.caption');
            if ($(this).val() == "") { $(labelCaption).removeClass("editing"); }
        });

    /******************************************************************/
    /* Blog Detail      			  */
    /******************************************************************/
    //related post scroller
    var $relatedPostCycle;
    if ($('#relatedPostHolder').length > 0) {
        $relatedPostCycle = $('#relatedPostHolder').cycle({
            fx: 'scrollHorz',
            slideExpr: 'li',
            next: '#nextPost',
            prev: '#prevPost',
            timeout: 0,
            cleartype: true
        }); //cycle    
    }

    /******************************************************************/
    /* scrolling gallery - adrenalin rush post*/
    /******************************************************************/
    if ($("#adrenalinTwo").length > 0) {
        //getting all photos inside photo sets
        $.getJSON("http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&photoset_id=72157626430772424&extras=url_s,date_upload&api_key=7551805dcd9021b8c3c469aebad50d10&user_id=43556769@N08&format=json&jsoncallback=?", function (data) {

            $.each(data.photoset.photo, function (i, photo) {
                var t = 'http://farm' + photo.farm + '.static.flickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '.jpg';
                var tempImg = $('<img class="scrollThumb" />')
                    .hide()
                    .load(function () {
                        $(this).fadeIn();
                        //console.log($(this).height());
                    })
                    .attr('src', t)
                    .attr('id', photo.dateupload);

                $(tempImg).appendTo($('#rushImages'));                
            });

            $(".scrollThumb").wrap("<div />")
        });
        // initialize scrollable
        $(".scrollGallery .scrollable").scrollable();
    }

    if ($("#adrenalinOne").length > 0) {
        //getting all photos inside photo sets
        $.getJSON("http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&photoset_id=72157625988424331&extras=url_s,date_upload&api_key=7551805dcd9021b8c3c469aebad50d10&user_id=43556769@N08&format=json&jsoncallback=?", function (data) {

            $.each(data.photoset.photo, function (i, photo) {
                var t = 'http://farm' + photo.farm + '.static.flickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '.jpg';
                var tempImg = $('<img class="scrollThumb" />')
                    .hide()
                    .load(function () {
                        $(this).fadeIn();
                        //console.log($(this).height());
                    })
                    .attr('src', t)
                    .attr('id', photo.dateupload);

                    $(tempImg).appendTo($('#rushImagesOne'));
            });

            $(".scrollThumb").wrap("<div />")
        });
        // initialize scrollable
        $(".scrollGallery .scrollable").scrollable();
    }

    if ($("#adrenalinThree").length > 0) {
        //getting all photos inside photo sets
        $.getJSON("http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&photoset_id=72157627166315522&extras=url_s,date_upload&api_key=7551805dcd9021b8c3c469aebad50d10&user_id=43556769@N08&format=json&jsoncallback=?", function (data) {

            $.each(data.photoset.photo, function (i, photo) {
                var t = 'http://farm' + photo.farm + '.static.flickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '.jpg';
                var tempImg = $('<img class="scrollThumb" />')
                    .hide()
                    .load(function () {
                        $(this).fadeIn();
                        //console.log($(this).height());
                    })
                    .attr('src', t)
                    .attr('id', photo.dateupload);

                $(tempImg).appendTo($('#rushImagesThree'));
            });

            $(".scrollThumb").wrap("<div />")
        });
        // initialize scrollable
        $(".scrollGallery .scrollable").scrollable();
    }
});

function ApplicationValidate(evt, element) {
    // Ascend from the button that triggered this click event 
    //  until we find a container element flagged with 
    //  .validationGroup and store a reference to that element.
    var $group;

    if (evt != null) {
        $group = $(evt.currentTarget).parents('.applicationForm:first');
    }
    else if (element != null) {
        $group = $(element).parents('.applicationForm:first');
    }

    var isValid = true;

    // Descending from that .validationGroup element, find any input
    //  elements within it, iterate over them, and run validation on 
    //  each of them.
    $group.find(':input').each(function (i, item) {
        //alert($(item).attr("id") + ":" + $(item).valid());
        if (!$(item).valid())
            isValid = false;
    });

    // If any fields failed validation, prevent the button's click 
    //  event from triggering form submission.
    if (!isValid) {
        if (evt != null) {
            evt.preventDefault();
        }
        return false;
    }
    return true;
}               
