/*
 * DFC Widget - jQuery Plugin
 * Written by Christophe LAFFONT
 * Requires: - jquery 1.3.x
 * Copyright (c) 2010 TWIST IMAGE (http://www.twistimage.com)
 * Dual licensed under the MIT and GPL licenses
 * Version: 1.0
 */
 
/* markup example for $("#dfc_header").DFCWidget();   
-----------------------------------------------------
    <div id="dfc_data" style="display:none;">
        <a href="http://www.dairygoodness.ca/100-canadian-milk" class="dfc_milk"><img src="http://<?php echo $domain ?>/img/l_100pourcent.png" alt="100% Canadian milk" /></a>
        <div class="dfc_center">
            <a href="http://www.dairygoodness.ca" class="dfc_logo"><img src="http://<?php echo $domain ?>/img/l_dairy-goodness.gif" alt="Dairy Goodness" /></a> 
            <ul id="dfc_nav">
                <li class="first" id="m_dfc_home"><a href="http://www.dairygoodness.ca">Home</a></li>
                <li id="m_dfc_recipes"><a href="http://www.dairygoodness.ca/recipes">Recipes</a></li>
                <li id="m_dfc_good-health"><a href="http://www.dairygoodness.ca/good-health">Good Health</a></li>
                <li id="m_dfc_good-life"><a href="http://www.dairygoodness.ca/good-life">Good Life</a></li>
            </ul>
        </div>
    </div>
	<noscript>
		<div id="dfc_widget" class="noscript">
			<div id="dfc_wrapper">
				<div id="dfc_data">
					<a href="http://www.dairygoodness.ca/100-canadian-milk" class="dfc_milk"><img src="http://<?php echo $domain ?>/img/l_100pourcent.png" alt="100% Canadian milk" /></a>
					<div class="dfc_center">
						<a href="http://www.dairygoodness.ca" class="dfc_logo"><img src="http://<?php echo $domain ?>/img/l_dairy-goodness.gif" alt="Dairy Goodness" /></a> 
					</div>					
				</div>
			</div>
		</div>
	</noscript>
 */
;(function ($) {

    /* Stand-alone function to create the Widget.*/
    $.DFCWidget = function (data, options) {
        return $.DFCWidget.impl.init(data, options);
    };

    /* Stand-alone close function */
    $.DFCWidget.close = function () {
        $.DFCWidget.impl.close();
    };

    /* Chained function to create a DFC Widget. */
    $.fn.DFCWidget = function (options) {
        return $.DFCWidget.impl.init(this, options);
    };

    /* DFC Widge default options */
    $.DFCWidget.defaults = {
        appendTo: 'body', // (String:'body') The jQuery selector to append the elements to.
        widgetAttrs: { id: 'dfc_widget' }, // (Object:{}) The Attributs for the widget div
        widgetCss: {}, // (Object:{}) The CSS styling for the widget div
        wrapperId: 'dfc_wrapper', // (String:'dfc_wrapper') The DOM element id for the wrapper div
        dataId: 'dfc_data', // (String:'dfc_data') The DOM element id for the data div
        dataCss: {}, // (Object:{}) The CSS styling for the data div
        minWidth: 970, // (Number: 960) The minimum with value for the container
        easing: { open: 'easeOutExpo', close: 'easeOutExpo' }, // (Object:{}) Animations, Transitions: http://gsgd.co.uk/sandbox/jquery/easing/
        effectDuration: 1000,  // (Number: 1000) number of ms for transition effect
        triggerEvent: 'mouseenter', // (String) trigger events: mouseover, mousedown, mouseup, click, dblclick
        onLoad: { show: true, delay: 1000 }, // (Object:{}) show the widget and number of ms to delay before hiding (on page load)
		onMouseOut: { autoHide: true, delay: 600 }, // (Object:{}) automatically hide the Widget when mouse leaves area and number of ms to delay before hiding (on mouseout)
        onOpen: null, // (Function:null) The callback function used in place of DFC Widget open
        onShow: null, // (Function:null) The callback function used after the widget has opened
        onClose: null, // (Function:null) The callback function used in place ofDFC Widget's close
		wtSite: ''
    };

    /* Main DFC Widget object */
    $.DFCWidget.impl = {
        /* DFC Widget options */
        o: null,
        /* Contains the DFC Widget elements and is the object passed 
         * back to the callback (onOpen, onShow, onClose) functions */
        d: {},
        /* Initialize the DFC Widget */
        init: function (data, options) {
            var s = this;

            // don't allow multiple calls
            if (s.d.data) { return false; }

            // merge defaults and user options
            s.o = $.extend({}, $.DFCWidget.defaults, options);

            // set default variables 
            s.w = { min: 0 };

            // set the onClose callback flag
            s.occb = false;

            // determine how to handle the data based on its type
            if (typeof data == 'object') {
                // convert DOM object to a jQuery object
                data = data instanceof jQuery ? data : $(data);
            }
            else if (typeof data == 'string' || typeof data == 'number') {
                // just insert the data as innerHTML
                data = $('<div></div>').html(data);
            }
            else {
                // unsupported data type!
                alert('Widget Error: Unsupported data type: ' + typeof data);
                return s;
            }

            // create the widget
            s.create(data);
            data = null;

            // Show the widget on page load
            if(s.o.onLoad.show) {
                s.closed = false;
				s.d.wrapper.css({ width: '100%' });

                if(s.o.onLoad.delay > 0) {
                    // let's hide the widget when the page is loading after {delay} milliseconds
                    s.onloadTimer = window.setTimeout( function() { s.close(); }, s.o.onLoad.delay);
                }
            }else {
				s.closed = true;
				s.expanded = false;
			}

            // Show the widget
			/*s.open();*/
			s.d.widget.css({visibility: ''});
            
            // useful for adding events/manipulating data
            if ($.isFunction(s.o.onShow)) {
                s.o.onShow.apply(s, [s.d]);
            }

            // don't break the chain =)
            return s;
        },
        /* Create and add the Widget container to the page */
        create: function (data) {
            var s = this;

            // create the widget
            s.d.widget = $('<div></div>')
                .attr(s.o.widgetAttrs)
                .css($.extend(s.o.widgetCss, { visibility: 'hidden' }))
				.width($(window).width() + 30)
                .appendTo(s.o.appendTo);

            // Add the wrapper
            s.d.wrapper = $('<div></div>')
                .attr('id', s.o.wrapperId)
                .appendTo(s.d.widget);

            // add the data
            s.d.data = data
                .attr('id', data.attr('id') || s.o.dataId)
                .css($.extend(s.o.dataCss, { display: 'inline', width: '100%' }))
                .appendTo(s.d.wrapper);

            data = null;

            // Keep the default Wrapper width
            s.defaultWidth = 305;
			s.expanded = true;
            // bind default events
            s.bindEvents();

        },
        /* Bind events */
        bindEvents: function () {
			
            var s = this;		
			var closeTimeDFCwidget = null;
			var closeDFCwidget = null;
			var expandDFCwidget = null;


            // bind event defined by {triggerEvent} to the trigger to open and close 
            if(s.o.triggerEvent){
                s.d.wrapper.bind(s.o.triggerEvent + '.DFCWidget', function(e) {
                    // if the trigger event is click or dblclick, we want to close the menu if its open
                    if((s.o.triggerEvent == 'click' ||s.o.triggerEvent == 'dblclick') && !s.closed) {
                        e.preventDefault();
                        s.close(); 
                    } else {
                        e.preventDefault();
						if(s.expanded == false){
							expandDFCwidget = window.setTimeout(function (){		
								s.expanded = true;					
								s.open();
							},1000);/*Time in ms before expanding after the mouseenter*/
			
						}else{		
							s.expanded = true;	
							if(closeTimeDFCwidget){window.clearTimeout(closeTimeDFCwidget);}
							if(closeDFCwidget){window.clearTimeout(closeDFCwidget);}
						}

                    }
                });
            }
			
			s.d.wrapper.mouseenter( function() { 
				if(s.onloadTimer){ window.clearTimeout(s.onloadTimer); }								
			});

            // if we want the widget to close auto
            if(s.o.onMouseOut.autoHide) {
                s.d.wrapper.mouseleave( function() { 
					if(expandDFCwidget) { 
						window.clearTimeout(expandDFCwidget); 
					}
					if(s.expanded) {
						closeTimeDFCwidget = window.setTimeout(function (){
							s.expanded = false;
							closeTimeDFCwidget = false;
						},1000);/*Time in ms before being able to expand again after the mouseleave*/			

						closeDFCwidget = window.setTimeout(function (){					
							s.close();
						},1000);/*Time in ms before closing after the mouseleave*/
					}
				});
            }else{
                // bind keydown events for Esc
                $(document).bind('keydown.DFCWidget', function (e) {
                    if (e.keyCode == 27) { // ESC
                        e.preventDefault();
                        s.close();
                    }
                });
            }
            
			// bind On Resize
			$(window).bind('resize.DFCWidget', function () {
				if(!s.closed){
					s.d.wrapper.trigger(s.o.triggerEvent + '.DFCWidget');
				}else {
					/*console.log((parseInt(s.d.widget.css('left')) + s.defaultWidth) + ' > ' + s.o.minWidth + '?');	
					if((parseInt(s.d.widget.css('left')) + s.defaultWidth) < s.o.minWidth) {
						s.d.widget.css('left', (s.o.minWidth - s.defaultWidth)); 		
					}else {
						s.d.widget.css('right', 0);	
					}*/
				}
				//Fix min-width for ie6/ie7 (browsers without native support)
				//if ($.browser.msie && $.browser.version < 8){ 
					//s.d.widget.css({width: ($(window).width() < s.o.minWidth) ? s.o.minWidth : '100%'});
				//}
			}).trigger('resize');
			
			// add WT tracking onClick
			$('.dfc_logo', '#'+s.o.widgetAttrs.id).live('click', function() {
				s.trackWT($(this).attr('href'), 'logo');
			});
			$('#m_dfc_home a', '#'+s.o.widgetAttrs.id).live('click', function() {
				s.trackWT($(this).attr('href'), 'home');
			});
			$('#m_dfc_recipes a', '#'+s.o.widgetAttrs.id).live('click', function() {
				s.trackWT($(this).attr('href'), 'recipes');
			});
			$('#m_dfc_good-health a', '#'+s.o.widgetAttrs.id).live('click', function() {
				s.trackWT($(this).attr('href'), 'good-health');
			});
			$('#m_dfc_good-life a', '#'+s.o.widgetAttrs.id).live('click', function() {
				s.trackWT($(this).attr('href'), 'good-life');
			});
			$('.dfc_milk', '#'+s.o.widgetAttrs.id).live('click', function() {
				s.trackWT($(this).attr('href'), '100%');
			});


        },
        /* Open the Widget elements */
        open: function () {
            var s = this;

            if ($.isFunction(s.o.onOpen)) {
                // execute the onOpen callback 
                s.o.onOpen.apply(s, [s.d]);
            }
            else {
                // display the remaining elements
                if(s.timeout) clearTimeout(s.timeout);
				s.d.widget.width($(window).width() + 30);
                s.d.wrapper
                    .stop()
                    .animate( 
                        { width: s.d.widget.width() }, 
                        { 
                            duration: s.o.effectDuration, 
                            easing: s.o.easing.open,
                            complete: function() {
                                s.closed = false;
                            }
                        }
                    );
            }
        },
        /* Close the Widget elements */
        close: function () {
            var s = this;

            // prevent close when Widget does not exist
            if (!s.d.data) { return false; }

            if ($.isFunction(s.o.onClose) && !s.occb) {
                // set the onClose callback flag
                s.occb = true;

                // execute the onClose callback
                s.o.onClose.apply(s, [s.d]);
            }
            else {
				
				s.d.wrapper
                    .stop()
					.animate(
                        { width: s.defaultWidth ? s.defaultWidth : 0 }, 
                        { 
                            duration: s.o.effectDuration, 
                            easing: s.o.easing.close,
                            complete: function() {
                                s.closed = true;
								s.expanded = false;
								s.d.widget.width(s.defaultWidth);
								/* ie6 fix */
								$('.dfc_center', s.d.widget).css('zoom', '1');
                            }
                        }
                    );
					
            }
        },
		/* WebTrends tracking for links */
		trackWT: function (url, eventDescription) {
			var s = this;
			//console.log(url + ' ' + s.o.wtSite + '/Campaign-header/' + eventDescription);
			dcsMultiTrack(
				'DCS.dcsuri', url,            // name/value pair for URL
				'WT.ti', s.o.wtSite + '/Campaign-header/' + eventDescription  // name/value pair for page title
			);
		}
    };
	
	
	/*  ------------------------------------------------------------------
    Plugin/Cookie ---------------------------------------------------- */
    $.DFCCookie = function(name, value, options) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';

            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    };
	
})(jQuery);


