/*
	Masked Input plugin for jQuery
	Copyright (c) 2007-2009 Josh Bush (digitalbush.com)
	Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
	Version: 1.2.2 (03/09/2009 22:39:06)
*/
(function(a){var c=(a.browser.msie?"paste":"input")+".mask";var b=(window.orientation!=undefined);a.mask={definitions:{"9":"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"}};a.fn.extend({caret:function(e,f){if(this.length==0){return}if(typeof e=="number"){f=(typeof f=="number")?f:e;return this.each(function(){if(this.setSelectionRange){this.focus();this.setSelectionRange(e,f)}else{if(this.createTextRange){var g=this.createTextRange();g.collapse(true);g.moveEnd("character",f);g.moveStart("character",e);g.select()}}})}else{if(this[0].setSelectionRange){e=this[0].selectionStart;f=this[0].selectionEnd}else{if(document.selection&&document.selection.createRange){var d=document.selection.createRange();e=0-d.duplicate().moveStart("character",-100000);f=e+d.text.length}}return{begin:e,end:f}}},unmask:function(){return this.trigger("unmask")},mask:function(j,d){if(!j&&this.length>0){var f=a(this[0]);var g=f.data("tests");return a.map(f.data("buffer"),function(l,m){return g[m]?l:null}).join("")}d=a.extend({placeholder:"_",completed:null},d);var k=a.mask.definitions;var g=[];var e=j.length;var i=null;var h=j.length;a.each(j.split(""),function(m,l){if(l=="?"){h--;e=m}else{if(k[l]){g.push(new RegExp(k[l]));if(i==null){i=g.length-1}}else{g.push(null)}}});return this.each(function(){var r=a(this);var m=a.map(j.split(""),function(x,y){if(x!="?"){return k[x]?d.placeholder:x}});var n=false;var q=r.val();r.data("buffer",m).data("tests",g);function v(x){while(++x<=h&&!g[x]){}return x}function t(x){while(!g[x]&&--x>=0){}for(var y=x;y<h;y++){if(g[y]){m[y]=d.placeholder;var z=v(y);if(z<h&&g[y].test(m[z])){m[y]=m[z]}else{break}}}s();r.caret(Math.max(i,x))}function u(y){for(var A=y,z=d.placeholder;A<h;A++){if(g[A]){var B=v(A);var x=m[A];m[A]=z;if(B<h&&g[B].test(x)){z=x}else{break}}}}function l(y){var x=a(this).caret();var z=y.keyCode;n=(z<16||(z>16&&z<32)||(z>32&&z<41));if((x.begin-x.end)!=0&&(!n||z==8||z==46)){w(x.begin,x.end)}if(z==8||z==46||(b&&z==127)){t(x.begin+(z==46?0:-1));return false}else{if(z==27){r.val(q);r.caret(0,p());return false}}}function o(B){if(n){n=false;return(B.keyCode==8)?false:null}B=B||window.event;var C=B.charCode||B.keyCode||B.which;var z=a(this).caret();if(B.ctrlKey||B.altKey||B.metaKey){return true}else{if((C>=32&&C<=125)||C>186){var x=v(z.begin-1);if(x<h){var A=String.fromCharCode(C);if(g[x].test(A)){u(x);m[x]=A;s();var y=v(x);a(this).caret(y);if(d.completed&&y==h){d.completed.call(r)}}}}}return false}function w(x,y){for(var z=x;z<y&&z<h;z++){if(g[z]){m[z]=d.placeholder}}}function s(){return r.val(m.join("")).val()}function p(y){var z=r.val();var C=-1;for(var B=0,x=0;B<h;B++){if(g[B]){m[B]=d.placeholder;while(x++<z.length){var A=z.charAt(x-1);if(g[B].test(A)){m[B]=A;C=B;break}}if(x>z.length){break}}else{if(m[B]==z[x]&&B!=e){x++;C=B}}}if(!y&&C+1<e){r.val("");w(0,h)}else{if(y||C+1>=e){s();if(!y){r.val(r.val().substring(0,C+1))}}}return(e?B:i)}if(!r.attr("readonly")){r.one("unmask",function(){r.unbind(".mask").removeData("buffer").removeData("tests")}).bind("focus.mask",function(){q=r.val();var x=p();s();setTimeout(function(){if(x==j.length){r.caret(0,x)}else{r.caret(x)}},0)}).bind("blur.mask",function(){p();if(r.val()!=q){r.change()}}).bind("keydown.mask",l).bind("keypress.mask",o).bind(c,function(){setTimeout(function(){r.caret(p(true))},0)})}p()})}})})(jQuery);

/*
 * jQuery Cycle Lite Plugin
 * http://malsup.com/jquery/cycle/lite/
 * Copyright (c) 2008-2011 M. Alsup
 * Version: 1.1 (03/07/2011)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires: jQuery v1.3.2 or later
 */
(function($){var ver="Lite-1.1";$.fn.cycle=function(options){return this.each(function(){options=options||{};if(this.cycleTimeout){clearTimeout(this.cycleTimeout);}this.cycleTimeout=0;this.cyclePause=0;var $cont=$(this);var $slides=options.slideExpr?$(options.slideExpr,this):$cont.children();var els=$slides.get();if(els.length<2){window.console&&console.log("terminating; too few slides: "+els.length);return ;}var opts=$.extend({},$.fn.cycle.defaults,options||{},$.metadata?$cont.metadata():$.meta?$cont.data():{});opts.before=opts.before?[opts.before]:[];opts.after=opts.after?[opts.after]:[];opts.after.unshift(function(){opts.busy=0;});var cls=this.className;opts.width=parseInt((cls.match(/w:(\d+)/)||[])[1])||opts.width;opts.height=parseInt((cls.match(/h:(\d+)/)||[])[1])||opts.height;opts.timeout=parseInt((cls.match(/t:(\d+)/)||[])[1])||opts.timeout;if($cont.css("position")=="static"){$cont.css("position","relative");}if(opts.width){$cont.width(opts.width);}if(opts.height&&opts.height!="auto"){$cont.height(opts.height);}var first=0;$slides.css({position:"absolute",top:0,left:0}).each(function(i){$(this).css("z-index",els.length-i);});$(els[first]).css("opacity",1).show();if($.browser.msie){els[first].style.removeAttribute("filter");}if(opts.fit&&opts.width){$slides.width(opts.width);}if(opts.fit&&opts.height&&opts.height!="auto"){$slides.height(opts.height);}if(opts.pause){$cont.hover(function(){this.cyclePause=1;},function(){this.cyclePause=0;});}var txFn=$.fn.cycle.transitions[opts.fx];txFn&&txFn($cont,$slides,opts);$slides.each(function(){var $el=$(this);this.cycleH=(opts.fit&&opts.height)?opts.height:$el.height();this.cycleW=(opts.fit&&opts.width)?opts.width:$el.width();});if(opts.cssFirst){$($slides[first]).css(opts.cssFirst);}if(opts.timeout){if(opts.speed.constructor==String){opts.speed={slow:600,fast:200}[opts.speed]||400;}if(!opts.sync){opts.speed=opts.speed/2;}while((opts.timeout-opts.speed)<250){opts.timeout+=opts.speed;}}opts.speedIn=opts.speed;opts.speedOut=opts.speed;opts.slideCount=els.length;opts.currSlide=first;opts.nextSlide=1;var e0=$slides[first];if(opts.before.length){opts.before[0].apply(e0,[e0,e0,opts,true]);}if(opts.after.length>1){opts.after[1].apply(e0,[e0,e0,opts,true]);}if(opts.click&&!opts.next){opts.next=opts.click;}if(opts.next){$(opts.next).bind("click",function(){return advance(els,opts,opts.rev?-1:1);});}if(opts.prev){$(opts.prev).bind("click",function(){return advance(els,opts,opts.rev?1:-1);});}if(opts.timeout){this.cycleTimeout=setTimeout(function(){go(els,opts,0,!opts.rev);},opts.timeout+(opts.delay||0));}});};function go(els,opts,manual,fwd){if(opts.busy){return ;}var p=els[0].parentNode,curr=els[opts.currSlide],next=els[opts.nextSlide];if(p.cycleTimeout===0&&!manual){return ;}if(manual||!p.cyclePause){if(opts.before.length){$.each(opts.before,function(i,o){o.apply(next,[curr,next,opts,fwd]);});}var after=function(){if($.browser.msie){this.style.removeAttribute("filter");}$.each(opts.after,function(i,o){o.apply(next,[curr,next,opts,fwd]);});};if(opts.nextSlide!=opts.currSlide){opts.busy=1;$.fn.cycle.custom(curr,next,opts,after);}var roll=(opts.nextSlide+1)==els.length;opts.nextSlide=roll?0:opts.nextSlide+1;opts.currSlide=roll?els.length-1:opts.nextSlide-1;}if(opts.timeout){p.cycleTimeout=setTimeout(function(){go(els,opts,0,!opts.rev);},opts.timeout);}}function advance(els,opts,val){var p=els[0].parentNode,timeout=p.cycleTimeout;if(timeout){clearTimeout(timeout);p.cycleTimeout=0;}opts.nextSlide=opts.currSlide+val;if(opts.nextSlide<0){opts.nextSlide=els.length-1;}else{if(opts.nextSlide>=els.length){opts.nextSlide=0;}}go(els,opts,1,val>=0);return false;}$.fn.cycle.custom=function(curr,next,opts,cb){var $l=$(curr),$n=$(next);$n.css(opts.cssBefore);var fn=function(){$n.animate(opts.animIn,opts.speedIn,opts.easeIn,cb);};$l.animate(opts.animOut,opts.speedOut,opts.easeOut,function(){$l.css(opts.cssAfter);if(!opts.sync){fn();}});if(opts.sync){fn();}};$.fn.cycle.transitions={fade:function($cont,$slides,opts){opts.cssBefore={opacity:0};opts.animOut={opacity:0};opts.animIn={opacity:1};}};$.fn.cycle.ver=function(){return ver;};$.fn.cycle.defaults={fx:"fade",timeout:4000,speed:1000,next:null,prev:null,before:null,after:null,height:"auto",sync:1,fit:0,pause:0,delay:0,slideExpr:null,cssBefore:{},cssAfter:{},animIn:{},animOut:{}};})(jQuery);


jQuery(function($) {
    //Hide the default text in a text field on click.
    $('input.default').focus(function() {if (this.value == this.defaultValue) this.value = '';});
    $('input.default').blur(function() {if (this.value == '') this.value = (this.defaultValue ? this.defaultValue : '');});

    $('.mask-phone').mask('(999) 999-9999');
    $('#Birthdate').mask('99/99/9999');

    //load ajax ads
    $.ajax({
        type: "GET",
        url: "/adverts/getlist",
        dataType: "xml",
        success: function(xml) {
            //$('#advert').append($('<div id="#ad-rotate">'));
            var ads = $('<div>').attr('id','ad-rotate');
            //ads.html('hi');
            $(xml).find("ad").each(function() {
                var html = $('<div>').addClass('ad').css('background-image','url(http://photos.mytradesdirect.com/adverts/'+$(this).attr('filename')+')');
                var link;
                if($(this).attr('link') != 'false') {
                    link = $('<a>').attr('href',$(this).attr('link'));
                    if($(this).attr('blank') == 'true') link.attr('target','_blank');
                }
                html.append(link);
                //ads.append($('div').css('background-image', "url(http://photos.mytradesdirect.com/adverts/"+$(this).attr('filename')+")"));
                //ads.append('<div class="ad" style="width:175px;background: url(http://photos.mytradesdirect.com/adverts/'+$(this).attr('filename')+') no-repeat"></div>');
                ads.append(html);
            })
            $('#advert').append(ads);

        },
        complete: function() {
            $('#ad-rotate').cycle({
                delay: 6000,
                speed: 500,
                cssBefore: { zIndex: 100 },
                cssAfter: { zIndex: 0}
            });
        }
    }
    );

    //login form
    $("#open-login-form").click(function(){ return false; });
    
    $('#open-login-form').qtip({
       content: {
             text: $('#login-form'),
             title: {
                text: 'Login',
                button: true
             }
          },
       style: {
          classes: 'ui-tooltip-light ui-tooltip-shadow ui-tooltip-rounded'
          
       },
       position: {
          my: 'top right', // Position my top left...
          at: 'bottom middle'
       },
       show: {
          effect: function(offset) {
             $(this).slideDown(100); // "this" refers to the tooltip
          }
       },
       hide: {
          event: 'unfocus'
       }
    });


    //QTip Bookmarks form.
    $('.bookmark').each(function()
    {
       $(this).qtip({
       content: {
             text: 'Loading',
             ajax: {
               url: $(this).attr('href') // Use the rel attribute of each element for the url to load
            },
             title: {
                text: 'Add Bookmark',
                button: true
             }
          },
       style: {
          classes: 'bookmark ui-tooltip-light ui-tooltip-shadow ui-tooltip-rounded'
       },
       position: {
          my: 'top right', // Position my top left...
          at: 'bottom middle'
       },
       show: {
          event: 'click',
          effect: function(offset) {
             $(this).slideDown(100); // "this" refers to the tooltip
          }
       },
       hide: {
          event: 'unfocus'
       }
     })}).click(function(){return false;});

   //QTip send message form in directory.
    $('.send-message').each(function()
    {
       $(this).qtip({
       content: {
             text: 'Loading',
             ajax: {
               url: $(this).attr('href') // Use the rel attribute of each element for the url to load
            },
             title: {
                text: 'Send Message',
                button: true
             }
          },
       style: {
          classes: 'send-message ui-tooltip-light ui-tooltip-shadow ui-tooltip-rounded'
       },
       position: {
          my: 'top right', // Position my top left...
          at: 'bottom middle'
       },
       show: {
          event: 'click',
          effect: function(offset) {
             $(this).slideDown(100); // "this" refers to the tooltip
          }
       },
       hide: {
          event: 'unfocus'
       }
     })}).click(function(){return false;});

   //QTip send message form - profile
    $('.profileDetails .send-message').each(function()
    {
       $(this).qtip({
       content: {
             text: 'Loading',
             ajax: {
               url: $(this).attr('href') // Use the rel attribute of each element for the url to load
            },
             title: {
                text: 'Send Message',
                button: true
             }
          },
       style: {
          classes: 'send-message ui-tooltip-light ui-tooltip-shadow ui-tooltip-rounded'
       },
       position: {
          my: 'top left', // Position my top left...
          at: 'bottom left'
       },
       show: {
          event: 'click',
          effect: function(offset) {
             $(this).slideDown(100); // "this" refers to the tooltip
          }
       },
       hide: {
          event: 'unfocus'
       }
     })}).click(function(){return false;});


    //change region
    $('#open-change-region').click(function(){ return false; });
    
    $('#open-change-region').qtip({
       content: {
             text: $('#change-region-form'),
             title: {
                text: 'Set Your Location',
                button: true
             }
          },
       style: {
          classes: 'ui-tooltip-light ui-tooltip-shadow ui-tooltip-rounded'
       },
       position: {
          my: 'top right', // Position my top left...
          at: 'bottom middle'
       },
       show: {
          effect: function(offset) {
             $(this).slideDown(100); // "this" refers to the tooltip
          }
       },
       hide: {
          event: 'unfocus'
       }
    });

    // $("#open-change-region").colorbox({width:"700px",height:"400px", inline:true, href:"#change-region-form"});
    $("#SettingRegionForm").ajaxForm({
        beforeSubmit: function() {
            $("#SettingRegionForm").hide();
            $("#loading-region").show();
            $("#region-error").hide();
        },
        resetForm:true,
        dataType: 'json',
        success: function(data) {

            
            if(!data.error) {
                var display = '<strong>We think we found you. Is this<sub>&nbsp;</sub>correct?</strong><br/><br/>';
                display += '<ul><li>' + data.name + ', ' + data.region + ', ' + data.country_long + '</li></ul>';
                
                $("#found-region").html(display);
                $("#found-region").show();
                $("#found-submit").show();
                $("#loading-region").hide();
            }
            else {
                $("#SettingRegionForm").show();
                $("#loading-region").hide();
                $("#region-error").show();
            }
    }});

    $("#region-again").click(function() {
        $("#SettingRegionForm").show();
        $("#found-region").hide();
        $("#found-submit").hide();
    });

    $("#set-region").click(function() {
        $.ajax({
            url: $(this).attr('href'),
            success: function(data) {
                location.reload();
            }
        });
        return false;
    })

    //delete messages in dashboard
    $(".dismiss-message").click(function() {
        if(confirm("Do you want to delete this message?")) {
            $.getJSON($(this).attr('href'),function(data) {
                //how do I pass in the .dismiss-message object?
                //ie reference the parent of this clicked link, because below doesn't work
                
            });
            $(this).parent('div').fadeOut("normal");
        }
        return false;
    });

    //delete bookmark
    $(".delete-bookmark").click(function() {
        if(confirm("Do you want to delete this bookmark?")) {
            $.getJSON($(this).attr('href'),function(data) {
                //how do I pass in the .dismiss-message object?
                //ie reference the parent of this clicked link, because below doesn't work
               
            });
             $(this).parent().parent('div').fadeOut("normal");
        }
        return false;
    })


});
