/*!
 * Scripts
 */
$.extend(true, Engine, {
    utils : {
        links : function(){
            $('a[rel*=external]').click(function(e){
                e.preventDefault();
                window.open($(this).attr('href'));
            });
            $("a[href='./'], a[href=#]").click(function(e) {e.preventDefault();});
        },
        mails : function(){
            $('a[href^=mailto:]').each(function(){
                var mail = $(this).attr('href').replace('mailto:','');
                var replaced = mail.replace('/at/','@');
                $(this).attr('href','mailto:'+replaced);
                if($(this).text() == mail) {
                    $(this).text(replaced);
                }
            });
        },
        url: function(str){
            return $.trim(str).toLowerCase().replace(/[^a-z0-9\_\.\+\&\;\']+/g, '-').replace(/[\-\s]+$/, '').replace(/^[\-\s]+/, '');
        }
    },
    ui : {
        listing : function() {
            $('#listing ul li a').each(function() {
                var label = $(this).html().toLowerCase();
                $(this).append(' <span>'+label+'</span>')
            });
        },
        details : function(){
            //telephone
            $('div.entry-a ul.details .tel').filter(":not(.logged)").each(function(){
                $(this).data('tel',$(this).text());
                $(this).html('<abbr class="value" title="Click to reveal!">' + ($(this).attr("rel") || "Telephone" ) + '</abbr>');
            }).one('click',function(e){
                e.preventDefault();
                $(this).html($(this).data('tel')).addClass("logged");
                $.post('/ajax/logphone', {publicId: $(this).attr('title')});
                $(this).attr('title', '');
            });

            //web
            $('div.profile-a ul.details a.url').one('click',function(e){
                e.preventDefault();
                $(this).text($(this).attr('href'));
            });

            $("li.web a").click(function(){
                var publicId = (/^weblink_/.test($(this).attr("id")) ? $(this).attr("id").substr(8)  : null );
                if(publicId){
                    $.post("/ajax/logwebsiteclick", {publicId: publicId});
                }
            });

            //mail
            $('div.entry-a ul.details a.email, div.profile-a ul.details a.email').fancybox({
                autoDimensions: false,
                centerOnScroll: true,
                width: 750,
                height: 513,
                type: "ajax"
            });
            /*$('div.profile-a ul.details a.email').one('click',function(e){
                e.preventDefault();
                $(this).text($(this).attr('href').replace('mailto:','')).attr("href", "/listing/emailbusiness?cid=" + $(this).attr("rel"));
                $(this).fancybox({
                    autoDimensions: false,
                    width: 750,
                    height: 575,
                    type: "ajax"
                });
            });*/

            // sharebox
            if($.browser.msie && parseInt($.browser.version,10) < 9) $('ul.sharebox').prepend('<li class="before">dfgdfgd</li>').parent('li').css('z-index','10');

            $('ul.sharebox').parent('li').find('span').click(function() {
                $(this).next('ul.sharebox').toggle();
            }).parent().mouseleave(function() {
                $(this).find('ul.sharebox').hide();
            });

            // coupons share buttons
            $('ul.sharebox').parent('li').find('a.share').click(function() {
                $(this).next('ul.sharebox').toggle();
            }).parent().mouseleave(function() {
                $(this).find('ul.sharebox').hide();
            });
        },
        lightbox : function(){
            $('a[rel*=fancybox]').fancybox();

            $('a[rel*=fancyframe]').each(function(){
                var width 	= 750;
                var height 	= 500;
                var classes = $(this).attr('class');

                var widths = classes.match(/w(\d+)/);
                var heights = classes.match(/h(\d+)/);

                if(widths != null) width = parseInt(widths[1]);
                if(heights != null) height = parseInt(heights[1]);

                $(this).addClass('iframe').fancybox({
                    width: width,
                    height: height,
                    padding: 0,
                    titleShow : false,
                    overlayColor: '#000',
                    overlayOpacity: 0.3,
                    autoDimensions: false,
                    centerOnScroll: true,
                    showNavArrows: false
                });
            });
            $('a.fancyclose').click(function(){
                parent.top.$('#fancy_close').trigger('click');
            });
        },
        backgrounds : function() {
            var $root = $('#backgrounds');
            var $list = $root.find('ul');
            var $current = $list.find('li a.active');
            $root.find('p').append('<span><span>'+$current.text()+'</span></span>'); // append selectbox with active label
            var $select = $root.find('p > span');
            $current.parent().appendTo($list); // put active at the end of the list
            var used = [];

            // toggle between list and select
            var toggle = function() {
                if($list.is(':visible')){
                    $list.hide();
                    $select.css('visibility','visible');
                } else {
                    $list.show();
                    $select.css('visibility','hidden');
                }
            };

            // toggle list
            $select.mouseenter(function() { toggle(); });
            $list.mouseleave(function() { toggle(); });

            // fetch all bg class names used
            var classnames = function() {
                var c = $('body').attr('class');
                var matches = c.match(/bg\-\w+/g);
                if(matches === null) return false;
                return matches;
            };

            // click
            $list.find('a').click(function() {
                if($(this).is('.active')) return false;
                var current = $(this).parent().attr('class');

                // remove other bg classnames and add current one
                var classes = classnames();
                if(classes !== false) for(var i = 0; i < classes.length; i++) $('body').removeClass(classes[i]);
                $('body').addClass(current);

                // change active element and alter the list
                $(this).addClass('active').parent().siblings().find('a.active').removeClass('active');
                $select.find('span').text($(this).text());
                $(this).parent().appendTo($list);

                toggle();

                // set cookie
                $.cookie('background', current, { expires: 365, path: '/' });

                return false;
            });

        },
        tabs : function() {
            var all = [];
            $('div.tabs-a ul li a').each(function() {
                all[all.length] = $(this).hrefId();
            });
            $('div.tabs-a ul li a').click(function() {
                if($(this).parent().is('.active')) return false;
                $(all.join(',')).hide();
                $($(this).hrefId()).show();
                $(this).parent().addClass('active').siblings().removeClass('active');

                $.cookie('tab-search', $(this).hrefId(), { expires: 0, path: '/' });
                return false;
            });

            $('div.map-mini-a p.switch a').click(function() {
                $('div.tabs-a ul li:last a').trigger('click');
                return false;
            });

            var tab = $.cookie('tab-search');
            if(tab) {
                $("div.tabs-a ul li a[href='" + tab + "']").trigger("click");
            } else{
                $('div.tabs-a ul li a:first').parent().addClass("active");
            }
        }
    },
    forms : {
        search : {
            examples : function() {
                $('div.search-a p.field').each(function() {
                    var $input = $(this).find('input');
                    var $span = $(this).find('span');
                    var opacity = true;
                    if($.browser.msie) opacity = false;

                    $input.focus(function() {
                        if(opacity === true) $span.css('opacity',0.5);
                    }).keydown(function() {
                        $span.hide();
                    }).blur(function() {
                        if($(this).val() === ''){
                            $span.show();
                            if(opacity === true) $span.css('opacity',1);
                        }
                    });

                    $span.click(function() {
                        $input.focus();
                    });

                    window.setTimeout(function(){if($input.val()===''){$span.show();}},50);
                });
            },
            filters : function(){
                $('div.filter-a').each(function() {
                    var $root = $(this);

                    if($root.parents('div.cols-a').size() > 0) return false;

                    var cfStatus = $.cookie('filter-status');
                    var sClass = (cfStatus == "open" ? "open" : "closed");

                    var toggler = $root.find("h3:first").addClass(sClass);
                    var cols = $root.find('div.column');
                    if(sClass == "open") cols.show();
                    else cols.hide();

                    toggler.find('a').click(function(e){
                        e.preventDefault();
                        $(this).parent().toggleClass('closed open');

                        if($(this).parent().attr("class") == "closed") cols.hide();
                        else cols.show();

                        var status = ($(this).parent().attr("class") == "closed" ? "closed" : "open");
                        $.cookie('filter-status', status, { expires: 0, path: '/' });
                    });
                    $root.prepend(toggler);
                });
            },
            autocomplete : function() {
                $("#what").autocomplete({
                    source: "/ajax/autocompletecateg",
                    open: function(event, ui){
                        var pattern = new RegExp($(this).val(), "i");
                        $("ul.ui-autocomplete li.ui-menu-item a").each(function(index){
                            var met = $(this).text().match(pattern);
                            if(met != null){
                                $(this).html($(this).text().replace(met, new String(met).bold()));
                            }
                        });
                    }
                });
                $("#where").autocomplete({
                    source: "/ajax/autocompletelocation",
                    open: function(event, ui){
                        var pattern = new RegExp($(this).val(), "i");
                        $("ul.ui-autocomplete li.ui-menu-item a").each(function(index){
                            var met = $(this).text().match(pattern);
                            if(met != null){
                                $(this).html($(this).text().replace(met, new String(met).bold()));
                            }
                        });
                    }
                });

                /*if($('div.search-a-slim').size() == 0){
                    $('body').addClass('home');
                }*/
            },
            distance : function() {
                var sync = true;

                $('div.filter-a div.distance').each(function() {
                    var $root = $(this);
                    $root.append('<div class="slider"><div class="slide"></div></div>').prepend('<p class="value">1km</p>');

                    var $slider = $root.find('div.slide');
                    var $input 	= $root.find('p.input input');
                    var $value 	= $root.find('p.value').text($input.val() + "km");

                    $slider.slider({
                        range: "min",
                        value: $input.val(),
                        min: 1,
                        max: 300,
                        step: 1,
                        slide: function(event, ui) {
                            $input.val(ui.value);
                            $value.text(ui.value+'km');
                            $('body').trigger('distance.sync',[ui.value,$slider]);
                        },
                        change : function(event, ui) {
                            $input.val(ui.value);
                            $value.text(ui.value+'km');
                        },
                        stop: function(event, ui){
                            filterForm("radius", (ui.value * 1000));
                        }
                    });
                });

                $('body').bind('distance.sync',function(event,value,element) {
						if(sync == true) $('div.filter-a div.distance div.slide').each(function() {
							$(this).slider("value", value);
						});
					});

                /*$('body').bind('distance.sync', function(event, value, element) {
                    if(sync == true) {
                        $('div.filter-a div.distance div.slide').each(function() {
                            $(this).slider("value", value);
                        });
                    }
                });*/
            },
            mainsearch: function(){
                $("#search-form").submit(function(event) {
                    event.preventDefault();
                }).validate({
                    rules: {
                        what:{
                            required: function(element){
                                return $("#where").val().length == 0;
                            }
                        },
                        where: {
                            required: function(element){
                                return $("#what").val().length == 0;
                            }
                        }
                    },
                    messages: {what: "", where: ""},
                    submitHandler: function() {
                        var what = ($.trim($("#what").val()) == "" ? "-" : $.trim($("#what").val()));
                        var where = ($.trim($("#where").val()) == "" ? "Ireland" : $.trim($("#where").val()));
                        var location = '/search/' + Engine.utils.url(where);

                        if(Engine.utils.url(what)) {
                            location += "/" + Engine.utils.url(what) + ($('#f-coupons').attr('checked') ? '?coupons=1' : '');
                        }
                        else {
                            location += ($('#f-coupons').attr('checked') ? '?coupons=1' : '');
                        }

                        document.location = location; 
                    }
                });

                if(eval($.cookie('three-boxes'))){
                    $("#who-field").css("display", "block");
                    $("div.search-a").addClass("three-boxes");
                    $("div.search-a form").addClass("three-boxes");
                    $("#f-three").attr("checked", "checked");
                }
                $("#f-three").click(function(){
                    $("div.search-a").toggleClass("three-boxes");
                    $("div.search-a form").toggleClass("three-boxes");
                    $("#who-field input").val("");
                    if($("div.search-a").hasClass("three-boxes")){
                        $("#who-field span").css({display: "inline", opacity: 1});
                    }
                    $.cookie('three-boxes', $("div.search-a").hasClass("three-boxes"), { expires: 0, path: '/' });
                });
            }
        },
        subscribe : function() {
            $('div.subscribe-a p.field label').compactize();
        },
        general : function() {
            $('input.value').each(function(){
                var title = $(this).attr('title');
                if(title != '' && $(this).val() === '') $(this).val(title);
            }).focus(function() {
                var title = $(this).attr('title');
                if($(this).val() === title) $(this).val('');
            }).blur(function() {
                var title = $(this).attr('title');
                if($(this).val() === '') $(this).val(title);
            });
        }
    },
    fixes : {
        css : function() {
            if($.browser.msie && parseInt($.browser.version) <= 7) {
                $('div.coupon-a, form.generic-a span.error').prepend('<span class="before" />');
                $('ol.steps-a li:first-child').filter('.active').addClass('first-active');
                $('ol.steps-a li:last-child').filter('.active').addClass('last-active');
            }
            $('div.cols-a').find('div.sidenav-a, div.w68').equalHeights();
            $('div.cols-a').find('div.sidenav-a, div.w69').equalHeights();
            $('div.cols-a').find('div.cols-b div.profile-a-small, div.cols-b div.events-a').equalHeights();
            $('div.bizboxes-a').find('> div.box').equalHeights();
        }
    },
    maps: {
        iconsPath: "/public/images/gmap/",
        defaultIcon: "/public/images/gmap/marker.png"
    },
    initBGClickable: function(url){
        var $body = $("body");
        if($body.hasClass("home")){
            $body.click(function(e){
                if(e.target.nodeName.toLowerCase() == 'body'){
                    if(url.indexOf("http") >= 0)
                        window.open(url);
                    else
                        window.open('http://' + url);
                }
            });
            $body.mouseover(function(e){
                $(this).css("cursor", (e.target.nodeName.toLowerCase() == 'body') ? "pointer" : "default");
            });
        }
    }
});

jQuery(function($) {
	Engine.utils.links();
	Engine.utils.mails();
	Engine.ui.listing();
	Engine.ui.backgrounds();
	Engine.ui.tabs();
    /*Engine.ui.categories();*/
    Engine.ui.details();
	Engine.ui.lightbox();
	Engine.forms.search.examples();
	Engine.forms.search.autocomplete();
	Engine.forms.search.filters();
	Engine.forms.search.distance();
	Engine.forms.search.mainsearch();
    Engine.forms.subscribe();
	Engine.forms.general();
	Engine.fixes.css();
    $(document).ajaxComplete(function() {
        Engine.utils.links();
        Engine.fixes.css();
    });
});

