/*
 * hardybox (for jQuery)
 * version: 1.0 (2/01/10)
 * Usage:
 * License: MIT
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
 *  $(document).ready(function() {
 *    $('a[rel*=hardybox]').hardybox()
 *  })
 *  or
 *  $('a.hardybox').hardybox(); this is the method for targetDiv loads
 *  example:
 *
 *  $(function() {
 *      $('a.hardybox').click(function(){
 *          $('a.hardybox').hardybox();
 *      }):
 *  })
 *
 *  example with ajax targetDiv:
 *
 *  $(function() {
 *      $('a.hardybox').click(function(){
 *          $('a.hardybox').hardybox(
 *              {targetDiv:'#ajax-load-area'}
 *          );
 *      }):
 *  })
 *
 *  or for a more dynamic approach place target load area as rel="#your_target_div":
 *
 *  $(function() {
 *      $('a.hardybox').click(function(){
 *          $('a.hardybox').hardybox(
 *              {targetDiv:$(this).attr('rel')}
 *          );
 *      }):
 *  })
 *
 *
 *
 *  <a href="#terms" rel="hardybox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="hardybox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="hardybox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 *
 *    $.hardybox('some html')
 *
 *  The above will open a hardybox with "some html" as the content.
 *
 *    $.hardybox(function($) {
 *      $.get('blah.html', function(data) { $.hardybox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The hardybox function can also display an ajax page or image:
 *
 *    $.hardybox({ ajax: 'remote.html' })
 *    $.hardybox({ image: 'dude.jpg' })
 *
 *  Want to close the hardybox?  Trigger the 'close.hardybox' document event:
 *
 *    $(document).trigger('close.hardybox')
 *
 *  hardybox also has a bunch of other hooks:
 *
 *    loading.hardybox
 *    beforeReveal.hardybox
 *    reveal.hardybox (aliased as 'afterReveal.hardybox')
 *    init.hardybox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.hardybox', function() { ...stuff to do after the hardybox and contents are revealed... })
 *
 */
(function($) {
  $.hardybox = function(data, klass) {
    $.hardybox.loading()

    if (data.ajax) fillHardyboxFromAjax(data.ajax)
    else if (data.image) fillHardyboxFromImage(data.image)
    else if (data.div) fillHardyboxFromHref(data.div)
    else if ($.isFunction(data)) data.call($)
    else $.hardybox.reveal(data, klass)
  }

  /*
   * Public, $.hardybox methods
   */

  $.extend($.hardybox, {
    settings: {
      targetDiv    : '',
      mask         : false,
      opacity      : 71,
      boxHeading   : '',
      theme        : '',
      overlay      : true,
      draggable    : false,
      loadingImage : '/skin/frontend/default/citydeals/hardybox/images/loading.gif',
      closeImage   : '/skin/frontend/default/citydeals/hardybox/images/CloseButton.gif',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      hardyboxHtml  : '\
    <div id="hardybox" style="display:none;"> \
      <div class="popup"> \
        <div class="hardy-heading"></div> \
        <div class="body"> \
            <div class="pop-content"> \
            </div> \
            <div class="cdfooter"> \
                <a href="#" class="close"> \
                    <img src="/skin/frontend/default/citydeals/hardybox/images/CloseButton.gif" title="close" class="close_image" /> \
                </a> \
            </div> \
        </div> \
      </div> \
    </div>'
    },

    loading: function() {
      init()
      if ($('#hardybox .loading').length == 1) return true
      showOverlay()

      $('#hardybox .pop-content').empty()
      $('#hardybox .body').children().hide().end().
        append('<div class="loading"><img src="'+$.hardybox.settings.loadingImage+'"/></div>')

      $('#hardybox').css({
        top:	getPageScroll()[1] + (getPageHeight() / 10),
        left:	385.5
      }).show()

      $(document).bind('keydown.hardybox', function(e) {
        if (e.keyCode == 27) $.hardybox.close()
        return true
      })
      $(document).trigger('loading.hardybox')
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.hardybox')
      if (klass) $('#hardybox .pop-content').addClass(klass)
      $('#hardybox .pop-content').append(data)
      $('#hardybox .loading').remove()
      $('#hardybox .body').children().fadeIn('normal')
      $(data).fadeIn(100).css({'z-index':200})
      $('#hardybox').css('left', $(window).width() / 2 - ($('#hardybox .pop-content').children(':first').css('width') / 2))
      $(document).trigger('reveal.hardybox').trigger('afterReveal.hardybox')
    },

    close: function() {
      $.cookie("lbtrue",true);
      $(document).trigger('close.hardybox');$(document).trigger('close.hardybox');$(document).trigger('close.hardybox');
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.hardybox = function(settings) {
    init(settings)

    function clickHandler() {
      $.hardybox.loading(true)

      // support for rel="hardybox.inline_popup" syntax, to add a class
      // also supports deprecated "hardybox[.inline_popup]" syntax
      var klass = this.rel.match(/hardybox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillHardyboxFromHref(this.href, klass)
      return false
    }

    return this.click(clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup hardybox on this page
  function init(settings) {
    if ($.hardybox.settings.inited) return true;
    else $.hardybox.settings.inited = true

    $(document).trigger('init.hardybox')
    makeCompatible()

    var imageTypes = $.hardybox.settings.imageTypes.join('|')
    $.hardybox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

    if (settings) $.extend($.hardybox.settings, settings)
    $('body').append($.hardybox.settings.hardyboxHtml)

   if($.hardybox.settings.theme!=''){
   $.hardybox.settings.closeImage=$.hardybox.settings.closeImage.replace( /images/g,'images/' +$.hardybox.settings.theme);
   }
    var preload = [ new Image(), new Image() ]
    preload[0].src = $.hardybox.settings.closeImage
    preload[1].src = $.hardybox.settings.loadingImage

    $('#hardybox').find('.b, .bl, .br, .tl, .tr').each(function() {
      preload.push(new Image())

      if($.hardybox.settings.theme!=''){
       $(this).css('background-image', $(this).css('background-image').replace( /images/g,'images/' +$.hardybox.settings.theme));

	  preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')

      }else{
          preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
      }
	if($.hardybox.settings.draggable===true){
		$('#hardybox').draggable();
		$('#hardybox').css({'cursor':'move'});
	}
    })
	if($.hardybox.settings.boxHeading != ''){
		$('td.hardy-heading').append($.hardybox.settings.boxHeading);
        }
    $('#hardybox .close').click($.hardybox.close)
    $('#hardybox .close_image').attr('src', $.hardybox.settings.closeImage)
  }

  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.hardybox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.hardyboxHtml = $s.hardybox_html || $s.hardyboxHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: image.extension (hardy.jpg)
  //    ajax: anything else
  function fillHardyboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      $.hardybox.reveal($(target).clone().show(), klass)

    // image
    } else if (href.match($.hardybox.settings.imageTypesRegexp)) {
      fillhardyboxFromImage(href, klass)
    // ajax
    } else {
      fillHardyboxFromAjax(href, klass)
    }
  }

  function fillHardyboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.hardybox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillHardyboxFromAjax(href, klass) {
	if($.hardybox.settings.targetDiv != ''){
		$.ajax({
		url: href,
		dataType:"html",
		cache: false,
		success: function(html){
		try{
			var tmp ='';
			tmp = $(html).find($.hardybox.settings.targetDiv).html();
			$.hardybox.reveal(tmp, klass)
                        $('.pop-content').html(tmp);
		}catch (e){
			alert('there was an error processing your request');
		}
		},
		error: function(e){
			$('.overlay_error').fadeIn('slow');
			$('.overlay_error').html('error: '+ e);
		}
		});
	}else{
		$.get(href, function(data) {$.hardybox.reveal(data, klass)})
	}
  }

  function skipOverlay() {
    return $.hardybox.settings.overlay == false || $.hardybox.settings.opacity === null
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('hardybox_overlay').length == 0)
      $("body").append('<div id="hardybox_overlay" class="hardybox_hide"></div>')


    $('#hardybox_overlay').hide().addClass("hardybox_overlayBG")
      .css('opacity', $.hardybox.settings.opacity)
      .click(function() {$(document).trigger('close.hardybox')})
      .fadeIn(200);
    if($.hardybox.settings.theme!=''){
       $('.hardybox_overlayBG').css('background-image', $('.hardybox_overlayBG').css('background-image').replace( /images/g,'images/' +$.hardybox.settings.theme));
    }
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#hardybox_overlay').fadeOut(200, function(){
      $("#hardybox_overlay").removeClass("hardybox_overlayBG")
      $("#hardybox_overlay").addClass("hardybox_hide")
      $("#hardybox_overlay").remove()
    })

    return false
  }

   /*
   * Bindings
   */

  $(document).bind('close.hardybox', function() {
    $(document).unbind('keydown.hardybox')
    $('#hardybox').fadeOut(function() {
      $('#hardybox .pop-content').removeClass().addClass('pop-content')
      hideOverlay()
      $('#hardybox .loading').remove()

    })
  })

})(jQuery);



/*
 * jQuery Idle function to chain time outs
 */

       jQuery.fn.idle = function(time)
      {
          var o = jQuery(this);
          o.queue(function()
          {
             setTimeout(function()
             {
                o.dequeue();
             }, time);
          });
          return this;              //****
      }
/*
 * Queued Ajax requests.
 * A new Ajax request won't be started until the previous queued
 * request has finished.
 */
jQuery.ajaxQueue = function(o){
	var _old = o.complete;
	o.complete = function(){
		if ( _old ) _old.apply( this, arguments );
		jQuery.dequeue( jQuery.ajaxQueue, "ajax" );
	};

	jQuery([ jQuery.ajaxQueue ]).queue("ajax", function(){
		jQuery.ajax( o );
	});
};
/**
 * @author alexander.farkas
 *
 * @version 2.5.4
 * project site: http://plugins.jquery.com/project/AjaxManager
 */
(function($){
	$.support.ajax = !!(window.XMLHttpRequest);
	if(window.ActiveXObject){
		try{
			new ActiveXObject("Microsoft.XMLHTTP");
			$.support.ajax = true;
		} catch(e){
			if(window.XMLHttpRequest){
				$.ajaxSetup({xhr: function(){
					return new XMLHttpRequest();
				}});
			}
		}
	}
	$.manageAjax = (function(){
		var cache 			= {},
			queues			= {},
			presets 		= {},
			activeRequest 	= {},
			allRequests 	= {},
			triggerEndCache = {},
			defaults 		= {
						queue: true, //clear
						maxRequests: 1,
						abortOld: false,
						preventDoubbleRequests: true,
						cacheResponse: false,
						complete: function(){},
						error: function(ahr, status){
							var opts = this;
							if(status && status.indexOf('error') != -1){
								setTimeout(function(){
									var errStr = status +': ';
									if(ahr.status){
										errStr += 'status: '+ ahr.status +' | ';
									}
									errStr += 'URL: '+ opts.url;
									throw new Error(errStr);
								}, 1);
							}
						},
						success: function(){},
						abort: function(){}
				}
		;

		function create(name, settings){
			var publicMethods = {};
			presets[name] = presets[name] ||
				{};

			$.extend(true, presets[name], $.ajaxSettings, defaults, settings);

			if(!allRequests[name]){
				allRequests[name] 	= {};
				activeRequest[name] = {};
				activeRequest[name].queue = [];
				queues[name] 		= [];
				triggerEndCache[name] = [];
			}
			$.each($.manageAjax, function(fnName, fn){
				if($.isFunction(fn) && fnName.indexOf('_') !== 0){
					publicMethods[fnName] = function(param, param2){
						if(param2 && typeof param === 'string'){
							param = param2;
						}
						fn(name, param);
					};
				}
			});
			return publicMethods;
		}

		function complete(opts, args){

			if(args[1] == 'success' || args[1] == 'notmodified'){
				opts.success.apply(opts, [args[0].successData, args[1]]);
				if (opts.global) {
					$.event.trigger("ajaxSuccess", args);
				}
			}

			if(args[1] === 'abort'){
				opts.abort.apply(opts, args);
				if(opts.global){
					$.active--;
					$.event.trigger("ajaxAbort", args);
				}
			}

			opts.complete.apply(opts, args);

			if (opts.global) {
				$.event.trigger("ajaxComplete", args);
			}

			if (opts.global && ! $.active){
				$.event.trigger("ajaxStop");
			}
			//args[0] = null;
		}

		function proxy(oldFn, fn){
			return function(xhr, s, e){
				fn.call(this, xhr, s, e);
				oldFn.call(this, xhr, s, e);
				xhr = null;
				e = null;
			};
		}


		function callQueueFn(name){
			var q = queues[name];
			if(q && q.length){
				var fn = q.shift();
				if(fn){
					fn();
				}
			}
		}


		function add(name, opts){
			if(!presets[name]){
				create(name, opts);
			}
			opts = $.extend({}, presets[name], opts);
			//aliases
			var allR 	= allRequests[name],
				activeR = activeRequest[name],
				queue	= queues[name];

			var id 				= opts.type +'_'+ opts.url.replace(/\./g, '_'),
				triggerStart 	= true,
				oldComplete 	= opts.complete,
				ajaxFn 			= function(){
									activeR.queue.push(id);
									activeR[id] = {
										xhr: false,
										ajaxManagerOpts: opts
									};
									activeR[id].xhr = $.ajax(opts);
									return id;
								}
				;

			if(opts.data){
				id += (typeof opts.data == 'string') ? opts.data : $.param(opts.data);
			}

			if(opts.preventDoubbleRequests && allRequests[name][id]){
				return false;
			}

			allR[id] = true;

			opts.complete = function(xhr, s, e){
				var triggerEnd = true;
				if(opts.abortOld){
					$.each(activeR.queue, function(i, activeID){
						if(activeID == id){
							return false;
						}
						abort(name, activeID);
						return activeID;
					});
				}
				oldComplete.call(this, xhr, s, e);
				//stop memory leak
				if(activeRequest[name][id]){
					if(activeRequest[name][id] && activeRequest[name][id].xhr){
						activeRequest[name][id].xhr = null;
					}
					activeRequest[name][id] = null;
				}
				triggerEndCache[name].push({xhr: xhr, status: s});
				xhr = null;
				activeRequest[name].queue = $.grep(activeRequest[name].queue, function(qid){
					return (qid !== id);
				});
				allR[id] = false;

				e = null;

				delete activeRequest[name][id];

				$.each(activeR, function(id, queueRunning){
					if(id !== 'queue' || queueRunning.length){
						triggerEnd = false;
						return false;
					}
				});

				if(triggerEnd){
					$.event.trigger(name +'End', [triggerEndCache[name]]);
					$.each(triggerEndCache[name], function(i, cached){
						cached.xhr = null; //memory leak
					});
					triggerEndCache[name] = [];
				}
			};

			if(cache[id]){
				ajaxFn = function(){
					activeR.queue.push(id);
					complete(opts, cache[id]);
					return id;
				};
			} else if(opts.cacheResponse){
				 opts.complete = proxy(opts.complete, function(xhr, s){
					if( s !== "success" && s !== "notmodified" ){
						return false;
					}
					cache[id][0].responseXML 	= xhr.responseXML;
					cache[id][0].responseText 	= xhr.responseText;
					cache[id][1] 				= s;
					//stop memory leak
					xhr = null;
					return id; //strict
				});

				opts.success = proxy(opts.success, function(data, s){
					cache[id] = [{
						successData: data,
						ajaxManagerOpts: opts
					}, s];
					data = null;
				});
			}

			ajaxFn.ajaxID = id;

			$.each(activeR, function(id, queueRunning){
				if(id !== 'queue' || queueRunning.length){
					triggerStart = false;
					return false;
				}
			});

			if(triggerStart){
				$.event.trigger(name +'Start');
			}
			if(opts.queue){
				opts.complete = proxy(opts.complete, function(){

					callQueueFn(name);
				});

				if(opts.queue === 'clear'){
					queue = clear(name);
				}

				queue.push(ajaxFn);

				if(activeR.queue.length < opts.maxRequests){
					callQueueFn(name);
				}
				return id;
			}



			return ajaxFn();
		}

		function clear(name, shouldAbort){
			$.each(queues[name], function(i, fn){
				allRequests[name][fn.ajaxID] = false;
			});
			queues[name] = [];

			if(shouldAbort){
				abort(name);
			}
			return queues[name];
		}

		function getXHR(name, id){
			var ar = activeRequest[name];
			if(!ar || !allRequests[name][id]){
				return false;
			}
			if(ar[id]){
				return ar[id].xhr;
			}
			var queue = queues[name],
				xhrFn;
			$.each(queue, function(i, fn){
				if(fn.ajaxID == id){
					xhrFn = [fn, i];
					return false;
				}
				return xhrFn;
			});
			return xhrFn;
		}

		function abort(name, id){
			var ar = activeRequest[name];
			if(!ar){
				return false;
			}
			function abortID(qid){
				if(qid !== 'queue' && ar[qid] && ar[qid].xhr){
					try {
						ar[qid].xhr.abort();
					} catch(e){}
					complete(ar[qid].ajaxManagerOpts, [ar[qid].xhr, 'abort']);
				}
				return null;
			}
			if(id){
				return abortID(id);
			}
			return $.each(ar, abortID);
		}

		function unload(){
			$.each(presets, function(name){
				clear(name, true);
			});
			cache = {};
		}

		return {
			defaults: 		defaults,
			add: 			add,
			create: 		create,
			cache: 			cache,
			abort: 			abort,
			clear: 			clear,
			getXHR: 		getXHR,
			_activeRequest: activeRequest,
			_complete: 		complete,
			_allRequests: 	allRequests,
			_unload: 		unload
		};
	})();
	//stop memory leaks
	$(window).unload($.manageAjax._unload);
})(jQuery);
