var c2m;
$(document).ready(function(){
    $('#gridview').bind('click', function(){
        $(".datalist").removeClass().addClass("datagrid");
        
    });
    
    $('#listview').bind('click', function(){
        $(".datagrid").removeClass().addClass("datalist");
        
    });
    
    $("#facet-close").click(function(){
        $("#facet-content").toggle("blind");
    });
    $("#facet-close").toggle(function(){
        $(this).addClass("facet-open");
    }, function(){
        $(this).removeClass("facet-open");
    });
    
    // Menu toggling
    var opened_menu = null, panelHasFocus = 'unknown';
    // show the panel based on rel attribute of the current hovered link
    $('#subnav li').hoverIntent(function(){
        // hide previously opened panel
        if (opened_menu) 
            $(opened_menu).hide();
        
        var link_id = $(this).attr('id');
        
        // get the position of the hovered element
        var pos = $(this).offset();
        
        var openPanel = 'div#' + link_id + '-dd';
        // get the panel near by hovered element now
        $(openPanel).css({
            'left': (pos.left) + 'px',
            'top': (pos.top + $(this).height() + 5) + 'px',
            'zIndex': '5000'
        });
        
        // finaly show the relevant hidden panel
        $(openPanel).fadeIn('fast');
        
        // this is currently opened
        opened_menu = $(openPanel);
        
        // hide it back when mouse arrow moves away
        opened_menu.hover(function(){
        }, function(){
            $(this).fadeOut('fast');
        });
        
    }, function(){
        var link_id = $(this).attr('id');
        var openPanel = 'div#' + link_id + '-dd';
        
    });
    // End Menu toogle
    $('body').click(function(){
        $('div.dropmenu').hide();
    });
    
    if (!c2m) 
        c2m = {};
    if (!c2m.utils) 
        c2m.utils = {};
    if (!c2m.ajax) 
        c2m.ajax = {};
    c2m.location={'county':'','region':'','city':'','latitude':'','longitude':''};
    c2m.openedMenu = null
    c2m.ajax = {}
    c2m.utils = {
        ISO8601ToMills: function(ds){
            var d = new Date();
            d.setISO8601(ds);
            // return d.toDateString()+ ' '+d.toLocaleTimeString();
            return d.getTime();
            
            
        },
        currentUTCTimeInMills: function(){
            var d = new Date();
            var localTime = d.getTime();
            // this method returns the time zone offset in minutes, so convert
			// this value to milliseconds for easier manipulation:
            console.log('tzoffset'+d.getTimezoneOffset());
            var localOffset = (d.getTimezoneOffset()) * 60000;
            var utcTime = localTime + localOffset
            return utcTime;
            
        },
        daysInMonth: function(m, y){
            return new Date(y, m, 0).getDate();
        },
        daysThisMonth: function(){
            var d = new Date();
            return this.daysInMonth(d.getMonth(), d.getFullYear());
        },
        getElapsed: function(ds){
            // var ct = this.currentUTCTimeInMills();
            var ct = new Date().getTime();
            
            var dt = this.ISO8601ToMills(ds);
            
            
            var min = Math.round(((ct - dt) / 1000) / 60), st = '';
            ;
            
            
            if (min < 60) {
                var st = "";
                st = (min <= 1) ? "minute" : "minutes";
                
            }
            else 
                if (min >= 60 && min < 1440) {
                    min = Math.round(min / 60);
                    st = (min <= 1) ? "hour" : "hours";
                }
                // 1440 -> total minutes in a day and 10080=total minutes in a
				// month
                else 
                    if (min >= 1440 && min < (this.daysThisMonth() * 1440)) {
                        min = Math.round((min / 60) / 24);
                        st = (min <= 1) ? "day" : "days";
                    }
                    else {
                        min = Math.round(((min / 60) / 24) / this.daysThisMonth());
                        st = (min <= 1) ? "month" : "months";
                    }
            
            di = min + " " + st + " ago";
            return di;
            // return this.ISO8601ToMills(ds);
        },
        
        uniqueId: function(){
            var timestamp = Number(new Date()).toString();
            var random = Math.random() * (Math.random() * 100000 * Math.random());
            var unique = new String();
            unique = timestamp + random;
            return unique;
        },
        slug:function(s){
         s=s.toLowerCase();
         return s.replace(" ","-");
        }
        ,
        createCookie: function(name,value,days) {
        	var expires="";
    		if (days) {
    			    				 
    			var date = new Date();
    			date.setTime(date.getTime()+(days*24*60*60*1000));
    			 expires = "; expires="+date.toGMTString();
    		}
    		
    		document.cookie = name+"="+value+expires+"; path=/";
    	},

    	 readCookie: function(name) {
    		var nameEQ = name + "=";
    		var ca = document.cookie.split(';');
    		for(var i=0;i < ca.length;i++) {
    			var c = ca[i];
    			while (c.charAt(0)==' ') c = c.substring(1,c.length);
    			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    		}
    		return null;
    	},

    	eraseCookie: function (name) {
    		createCookie(name,"",-1);
    	},
    	
    	getIPLocation : function(ip) {
			var yql = 'select latitude,longitude from pidgets.geoip'+
								' where ip="'+ip+'"';
			c2m.utils.YQLQuery(yql,'gotGeo', 'http://datatables.org/alltables.env');

		},
		
		gotGeo : function(response) {
			var loc = response.query.results.Result;
			c2m.location.country=loc.country_code;
		      c2m.location.region=loc.region;
		      c2m.location.city=loc.city;
		      c2m.location.latitude=loc.latitude;
		      c2m.location.longitude=loc.longitude;
		      c2m.utils.createCookie('c2m.loc',loc.address.country+"|"+loc.address.region+"|"+loc.address.city+"|"+loc.latitude+"|"+loc.longitude);
	
		},

		YQLQuery : function(query, callback, table) {
			var src = 'http://query.yahooapis.com/v1/public/yql?q='+
								encodeURIComponent(query) + '&format=json&callback=' + callback; 
			if(table)
			  src += "&env=" + table;
			var head = document.getElementsByTagName('head')[0];
			var s = document.createElement('script');
			s.setAttribute('src',src);
			s.setAttribute('type', 'text/javascript');
			head.appendChild(s);
		},
		
		nearBy: function(point)
		{
			$.ajax({
			    type: "GET",
			    url: "http://www.click2money.com/nearby/"+point+"&callback=jsonptrex",
			    datatype:'json',
			    success: function(response){
			       	var data= $.parseJSON(response);
			       	if (data.locationName) {
			    	$('#region > a').attr('href','/local-deals/'+data.locationSlug);
			    	$('#region > a > span').html(data.locationName+' deals');
			    	}
			    
			    },
			    
			    error: function(){
				   if (console) console.log("error");
			    },
			    
			    complete: function(){
			    	
			    }
			    });	
		},
		calculate:function(t)
		{
			var now = new Date();
	        var millis = t - c2m.utils.currentUTCTimeInMills();//t - now.getTime();
	        console.log('t'+t);
	        console.log('utc'+c2m.utils.currentUTCTimeInMills());
	        
	        if (millis < 0) {
	            return "Expired";
	        }
	 
			var remaining = Math.floor(millis / 1000);
	        var days = Math.floor(remaining / (3600*24));
	        var daysRemaining = remaining % (3600*24);
	        var hours = Math.floor(daysRemaining / 3600);
	        var hoursRemaining = daysRemaining % 3600;
	        var minutes = Math.floor(hoursRemaining / 60);
	        var seconds = Math.floor(hoursRemaining % 60);
	        var result = "";
	        if (days != 0) {
	            result = days + "d ";
	        }
	        result += hours + "h " + minutes + "m " + seconds + "s";
	        return result;
		}
		
        
    }
 	
Date.prototype.setISO8601 = function(dString){

    var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;
    
    if (dString.toString().match(new RegExp(regexp))) {
        var d = dString.match(new RegExp(regexp));
        var offset = 0;
        
        this.setUTCDate(1);
        this.setUTCFullYear(parseInt(d[1], 10));
        this.setUTCMonth(parseInt(d[3], 10) - 1);
        this.setUTCDate(parseInt(d[5], 10));
        this.setUTCHours(parseInt(d[7], 10));
        this.setUTCMinutes(parseInt(d[9], 10));
        this.setUTCSeconds(parseInt(d[11], 10));
        if (d[12]) 
            this.setUTCMilliseconds(parseFloat(d[12]) * 1000);
        else 
            this.setUTCMilliseconds(0);
        if (d[13] != 'Z') {
            offset = (d[15] * 60) + parseInt(d[17], 10);
            offset *= ((d[14] == '-') ? -1 : 1);
            this.setTime(this.getTime() - offset * 60 * 1000);
        }
    }
    else {
        this.setTime(Date.parse(dString));
    }
    return this;
};

// Replaces all instances of the given substring.
String.prototype.replaceAll = function(strTarget, // The substring you want to
													// replace
 strSubString // The string you want to replace in.
){
    var strText = this;
    var intIndexOfMatch = strText.indexOf(strTarget);
    
    // Keep looping while an instance of the target string
    // still exists in the string.
    while (intIndexOfMatch != -1) {
        // Relace out the current instance.
        strText = strText.replace(strTarget, strSubString)
        
        // Get the index of any next matching substring.
        intIndexOfMatch = strText.indexOf(strTarget);
    }
    
    // Return the updated string with ALL the target strings
    // replaced out with the new substring.
    return (strText.toString());
};
var location = 'Unable to determine your location.';

cookie=	c2m.utils.readCookie('c2m.loc');
if (cookie) {

	var arr=cookie.split("|");
	c2m.location.country=arr[0];	 
	 c2m.location.region=arr[1];
      c2m.location.city=arr[2];
      c2m.location.latitude=arr[3];
      c2m.location.longitude=arr[4];
}	  
else {

if (google.loader.ClientLocation) {
  var loc = google.loader.ClientLocation;
   
  c2m.location.country=(loc.address.country)||'';
  c2m.location.region=loc.address.region||'';
  c2m.location.city=loc.address.city||'';
  c2m.location.latitude=loc.latitude||0;
  c2m.location.longitude=loc.longitude||0;
  c2m.utils.createCookie('c2m.loc',c2m.location.country+"|"+c2m.location.region+"|"+c2m.location.city+"|"+c2m.location.latitude+"|"+c2m.location.longitude,100);
}
}


	if (c2m.location.latitude)	
	c2m.utils.nearBy(c2m.location.latitude+","+c2m.location.longitude);	




	// Do a live query to pull sidebar listing
	if ($('div#wb_a')) {
		$.ajax({
		    type: "GET",
		    url: "/query",
		    dataType: 'html',
		    data: {
		  // 's': "<?php echo
			// addslashes(Inflector::slug($deal['title'],'+'))?>",
		  // 'id':"<?php echo $deal['key']?>",
		    'template':"listwidget",
		    'annotate':0,
		    'site':'4,5'
		    },
		    
		    success: function(html){
		    $('div#wb_a').html(html);
		    
		    },
		    
		    error: function(){
		    },
		    
		    complete: function(){
		    }
		    });
	}
	
	
	if ($('div#c2').length){
		$.ajax({
		    type: "GET",
		    url: "/query",
		    dataType: 'html',
		    data: {
		   'pt': c2m.location.latitude+","+c2m.location.longitude,
		    'template':"cl",
		    'annotate':0,
		    'site':'dd_n'
		    },
		    
		    success: function(html){
		     
		    $('#c2').html(html);
		     $("#deals_slider").wtScroller({
					num_display:3,
					slide_width:300,
					slide_height:182,
					slide_margin:20,
					button_width:20,
					ctrl_height:20,
					margin:15,	
					auto_scroll:true,
					delay:4000,
					scroll_speed:1000,
					easing:"",
					move_one:false,
					display_buttons:true,			
					display_scrollbar:false,
					display_indexes:true,
					display_caption:true,
					mouseover_caption:false,
					caption_align:"bottom",
					caption_position:"outside",					
					cont_nav:true,
					shuffle:false,
					lightbox_on:false
					
				});
		     if (c2m.location.latitude)
		     $("#locbar #msg").html("Wrong Location? <a href='/local-deals'>Click Here</a>");
		    	
		    },
		    
		    error: function(){
		    },
		    
		    complete: function(){
		    }
		    });
		
	

		}
	
	
    // Set counters
	var counter=function(){
		var it=$(".timecounter");
		
		if (!$(it).is(":empty"))
		$.each(it,function(){
			
			$(this).find(".counter").html((c2m.utils.calculate($(this).children(".mills").html())));
			$(this).show();
			
		});
		//setTimeout(counter,1000);
	}
	
	counter();
	

});

