/* DK new stuff */ 

//this is used to preserve coupon vs. store view after ajax call
var COUPON_VIEW = 1; 
//this is used to track which coupon we just clicked 'dislike' on
var DISLIKE_ID = 0; 
//this is used to track which item we just clicked 'favorite' on
var CURRENT_FAVORITE_ID = 0; 
//this is used to track which type of item we just clicked 'favorite' on
var CURRENT_FAVORITE_TYPE = '';


/* global variable for coupon code window */
var couponDialogue = null;


var replaceSpace = /\s+/g;


//$("#header-search-field").keyup(function(event) {

//});

var highlightPos = -1;
var searchLength = 0;
var searchQuery = null;
function highlightResult(dir) {
	if (dir == 40) {
	// down key pressed
		if ((highlightPos + 1) < searchLength) {
			highlightPos++;
			$("#search-overlay-middle").find('li').removeClass("search-overlay-list-active");
			var list = $("#search-overlay-middle").find('li').get(highlightPos);
			$(list).addClass("search-overlay-list-active");
			var livelink = $("#search-overlay-middle").find('li.search-overlay-list-active a').attr('href');	
			if (livelink != undefined && livelink.indexOf('search')>=0) {
				$("#header-search-field").val($(list).find('a').text());
			}
		}
	} else if (dir == 38) {
	// up key pressed	
		if (highlightPos > 0) {
			highlightPos--;
			$("#search-overlay-middle").find('li').removeClass("search-overlay-list-active");
			var list = $("#search-overlay-middle").find('li').get(highlightPos);
			$(list).addClass("search-overlay-list-active");
			var livelink = $("#search-overlay-middle").find('li.search-overlay-list-active a').attr('href');	
			if (livelink != undefined && livelink.indexOf('search')>=0) {
				$("#header-search-field").val($(list).find('a').text());
			}
		} else if (highlightPos == 0) {
			highlightPos = -1;
			$("#search-overlay-middle").find('li').removeClass("search-overlay-list-active");
			$("#header-search-field").val(searchQuery);
		}
	}
}

$("li", "#search-overlay-middle").hover(
	function () {
		$("#search-overlay-middle").find('li').removeClass("search-overlay-list-active");
		highlightPos = $("li", "#search-overlay-middle").index(this);
		var list = $("#search-overlay-middle").find('li').get(highlightPos);
		$(list).addClass("search-overlay-list-active");
		
	}, 
	function () {
		highlightPos = $("li", "#search-overlay-middle").index(this);
		var list = $("#search-overlay-middle").find('li').get(highlightPos);
		$(list).removeClass("search-overlay-list-active");
	}
);



/* ******************** END HEADER SEARCH FIELD ******************** */



//$("#header-search-field").keypress(search_monitor);

var search_process;

function search_monitor(e) {
	clearTimeout(search_process);		
	search_process = setTimeout(liveSearch, 275);
}

function search_monitor_pre(e) {
	if (e.keyCode == '13') {
		//enter key
		//find current hilighted link
		var livelink = $("#search-overlay-middle").find('li.search-overlay-list-active a').attr('href');	
		
		if (livelink != undefined) {
			e.preventDefault();
			window.location = livelink; 		
		}			
		
	} else if (e.keyCode == '8') {
		//backspace
		search_monitor(e);
	} 
	else if (e.keyCode == "27") {
	// escape key pressed
		$("#search-overlay").hide();
		$("#search-overlay-middle").find('li').removeClass("search-overlay-list-active");
		highlightPos = -1;
		//$(this).val('');
		//$(this).blur();
	} else if (e.keyCode == "40") {
	// down key pressed
		highlightResult(40);
	} else if (e.keyCode == "38") {
	// up key pressed
		highlightResult(38);
	} else {
	// a value has been entered
		//alert(searchLength);
		//$("#search-overlay").show();	
		
		//$("#debugText").html("yes");
		//perform search
		search_monitor(e);
	}

	if ($(this).val() == '') {
	// the field has been cleared
		//$("#search-overlay").hide();
	}
}


//populate "Live Search" results
function liveSearch() {

	//reset highlight pos on new search
	highlightPos = -1;
	var my_process = search_process; 
	
	//alert($("#CouponSearchForm").serialize());

	
        $('#search-ajax-loader').show();

        $.post("/coupons/liveSearch/", $("#CouponSearchForm").serialize(), function(data){
                //$("#debugText").html("my_proc: "+my_process+"; search_proc: "+search_process);

                if (my_process == search_process) {
                        //alert(data);
                        $("#search-overlay").html(data);
                        $("#search-overlay").show();
                        $('#search-ajax-loader').hide();

                        searchQuery = $("#header-search-field").val();
                        searchLength = $("#search-overlay-middle").find('li').length;
                }


        });
	
	
}

/* - end live search - */


/* registration error checking */

var register_process;

function register_monitor() {
	clearTimeout(register_process);		
	register_process = setTimeout(checkRegistrationFields, 250);
}
function email_monitor() {
	clearTimeout(register_process);		
	register_process = setTimeout(checkEmail, 250);
}

function checkRegistrationFields() {

        if(!$("#registerBox #UserPassword").val().length){
            alert("You must type in a password.")
            return false;
        }
	
	return true;

}

function checkEmail() {
	
	var email = $("#registerBox #UserEmail");

	$.post("/users/checkEmail/", $("#UserRegisterForm").serialize(), function(data){
	
		if (data == 1) {
			email.removeClass('error');
			return true; 
		} else {
			email.addClass('error');
			return false; 
		}
	});
	
	return false; 
}


/* -- end registration error checking -- */

var slider;

function sliderPrev(){
    slider.previousSlide();
}
function sliderNext(){
    slider.nextSlide();
}


$(document).ready(function(){

        /* init advanced slider */
        slider = $('#adv-slider').advancedSlider({
            width: 581,
            height: 290,
            timerAnimation: false,
            effectType: 'slide',
            navigationArrows: false,
            slideshowControls: false,
            slideMask: true,
            horizontalSlices: 1,
            verticalSlices: 1,
            slicePattern: 'topToBottom',
            sliceFade: false,
            alignType: 'centerCenter',
            slideshow: true,
            slideshowDelay: 7000
        });

        //$('#adv-slider').hover(function(){}, function(){});

        /* homepage ajax sorts */
        $('#sort_gifts').change(function(){
            var typeId = $(this).val();
            $.post("/coupons/ajax_sort_gifts/"+typeId, function(data){
                $("#giftsAjaxWrapper").html(data);

                //add compare onclick event
                $(".compare").bind('click', function(){

                    var list_id = $(this).closest(".compare-targets").attr("id");

                    var url_list = new Array();
                    $("#"+list_id+" li input:checked").each(function(){
                        url_list.push($(this).val());
                    });

                    windowPopEvent(url_list);

                });


            });
        });

        $('#sort_merchants').change(function(){
            var typeId = $(this).val();
            $.post("/coupons/ajax_sort_merchants/"+typeId, function(data){
                $("#featuredMerchantsAjaxWrapper").html(data);
            });
        });

        $('#sort_coupons').change(function(){
            var typeId = $(this).val();
            if(typeId==""){
                typeId = 0;
            }
            var listId = $(this).attr('list_id');
            $.post("/coupons/ajax_sort_coupons/"+typeId+"/"+listId, function(data){
                $("#couponsAjaxWrapper").html(data);

                if($("#couponsAjaxWrapper").find(".moreCoupons").size()){
                    $(".revealCoupons").show();
                } else {
                    $(".revealCoupons").hide();
                }

            });
        });
        
        $(".blink").each(function(){
            $(this).val($(this).attr('default'));
        }).focus(function(){
            if($(this).val()==$(this).attr('default')){
                $(this).val("");
            }
        }).blur(function(){
            if($(this).val()==""){
                $(this).val($(this).attr('default'));
            }
        });
        
        /* register infusionsoft email */
        $('#email_signup_form').submit(function(){
            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            if(reg.test($('#contact-email').val()) == false) {
                alert('Invalid Email Address');
                return false;
            }
            $.post("/users/ajaxemail/", $(this).serialize(), function(data){
                $('#email_signup_init').hide();
                $('#email_signup_success').show();
            });
            return false;
        });
        
        


	/* live search */
	$("#header-search-field").keydown(search_monitor_pre);
	
	/* ******************** START HEADER SEARCH FIELD ******************** */
	$("#header-search-field").focus(function() {
		if ($(this).val() == 'What are you shopping for?' || $(this).val() == ''){
                        $(this).val('');
                        liveSearch();
                }
                
	});
	
	$("#header-search-field").blur(function() {
		if ($(this).val() == '') {
			$(this).val('What are you shopping for?');
			$("#search-overlay").hide();
		}
	});


	//registration error checking
        //
	//$("#header-join-overlay-form #UserFname").keypress(register_monitor);
	//$("#header-join-overlay-form #UserLname").keypress(register_monitor);
	$("#registerBox #UserEmail").keypress(email_monitor);
	//$("#registerBox #UserPassword").keypress(register_monitor);
	//$("#header-join-overlay-form #UserPasswordConfirm").keypress(register_monitor);

	
	//check first dislike option by default
    var $radios = $('input:radio[name=rating-overlay]');
    if($radios.is(':checked') === false) {
        $radios.filter('[value=1]').attr('checked', true);
    }


	// DK additions for Cake messages and forms
	$("#flashMessage").click(function(e) {
		$("#flashMessage").fadeOut();
	});
	$("#authMessage").click(function(e) {
		$("#authMessage").fadeOut();
	});

	$('.UserLoginForm').submit(function() {
            
		//var self = $(this);
		$.post("/users/ajaxlogin/", $(this).serialize(), function(data){
                    
			if (data != '0') {
				//$("#debugText").html(data);
				window.location = data;
			} else {
				//show 'incorrect email/pw' message
				//favoriteTabError(true);
			}			
		});		
		
		return false;
	});

	/* -- forum character counter --*/
	$('#ForumDiscussionTitle').charCounter(150);
	$('#ForumDiscussionContent').charCounter(2000);
	$('#ForumCommentContent').charCounter(2000);

	$('#UserRegisterForm').submit(function() {
	
		if (!checkRegistrationFields()) {
			return false;
		}
	
		$.post("/users/ajaxRegister/", $(this).serialize(), function(data){
	
			var result = $.parseJSON(data); 
			
			if (result.success) {
				//$("#debugText").html(data);
				window.location = result.success;
			} else {
				alert(result.errors);
				//alert('Please check the form and try again.')
			}
		});		
		
		return false;
	});
	
	$('#UserForgotPasswordForm').submit(function() {

		$.post("/users/forgotPassword/", $(this).serialize(), function(data){

			var result = $.parseJSON(data); 
			
			if (result.status == 'success') {
				//close forgot pw 
				$("#header-signin-overlay-forgot-form").slideToggle();
				alert (result.message);
				forgotTabError(false);
			} else {
				forgotTabError(true);
			}
			
		});		

		return false; 
	});	


	$('#sidebar-my-favourites-coupons-top').live('click', function() {
		myCouponsSidebarHighlight('coupons');
	});


	//highlight the "my coupons" section that we just clicked on
	$('.mycoupons-ajax-link a.ajax-loader').live('click', function() {
		
		var papa = $(this).closest('ul').prev();
		var divid = papa.attr('id');

		var type = divid.split('sidebar-my-favourites-')[1].split('-top')[0];
		myCouponsSidebarHighlight(type);

		//myCouponsSidebarHighlight('coupons');
	});

 
	/* ajax paging */ 

	$('#column-page-nav a, #sidebar-my-favourites-coupons-top, .mycoupons-ajax-link a.ajax-loader').live('click', function() {

		var url = $(this).attr("href");
		url = url.replace(replaceSpace,'+')
		
		//console.log(url);

		$("#modalPopup").modal({
				opacity: 50,
				position: ['20%','32%']
			
		});
		
		$('#paginated').load(url, function() {
			ajaxOnComplete();
		});
		return false;
	});
	$('#column-nav a').live('click', function() {
		var url = $(this).attr("href");
		url.replace(replaceSpace,'+')
		
		$("#modalPopup").modal({
				opacity: 50,
				position: ['60%','32%']
			
		});
		
		$('#paginated').load(url, function() {
			ajaxOnComplete();
		});
		return false;
	});
	

	$(window)._scrollable(); // When scrolling the window
	

         
         if(navigator.plugins ["Shockwave Flash"]){
             /* clipboard */
             attachClipboardSWFs();
         }
	
}); 

/* --------GET SATISFACTION------- */ 
function openGSFN(type) {
  var feedback_widget_options = {};

  feedback_widget_options.display = "overlay";  
  feedback_widget_options.company = "couponpal";
  feedback_widget_options.placement = "hidden";
  feedback_widget_options.container = "get-satisfaction";
  feedback_widget_options.color = "#440800";
  feedback_widget_options.style = type;
  feedback_widget_options.limit = "3";
  

  var feedback_widget = new GSFN.feedback_widget(feedback_widget_options);
  feedback_widget.show();
	
}
/* ---------------- */ 

//set the ibar opt-in for this merchant to yes/no
function merchant_ibar(merch_id) {
	if ($("#merchant-ibar-"+merch_id +":checked").val()) {
		$.post('/merchants/ibar/'+merch_id+'/1', '', function (data) {
			//console.log(data);		
		});
	
	} else {
		$.post('/merchants/ibar/'+merch_id+'/0', '', function (data) {
			//console.log(data);		
		});
	}
}


//automatically favorite the item upon logging in 
function loginAndFavorite() {
	$("#favorite-item-id").val(CURRENT_FAVORITE_ID);
	$("#favorite-item-type").val(CURRENT_FAVORITE_TYPE);
	$("#UserLoginForm2").submit();
}

function loginAndDiscuss() {
	$("#forum-login").val(1);
	$("#UserLoginForm2").submit();
}

function myCouponsSidebarHighlight(type) {
	$("#sidebar-my-favourites-coupons-top").removeClass('sidebar-my-favourites-coupons-active');
	$("#sidebar-my-favourites-stores-top").removeClass('sidebar-my-favourites-stores-active');
	$("#sidebar-my-favourites-searches-top").removeClass('sidebar-my-favourites-searches-active');
	$("#sidebar-my-favourites-lists-top").removeClass('sidebar-my-favourites-lists-active');
	$("#sidebar-my-favourites-categories-top").removeClass('sidebar-my-favourites-categories-active');

	$("#sidebar-my-favourites-"+type+"-top").addClass('sidebar-my-favourites-'+type+'-active');

}

function changeCouponLimit() {

        /*
	$("#modalPopup").modal({
			opacity: 50,
			position: ['20%','32%']		
	});
    */

	$.post($('#showAmount').attr('action'), $("#showAmount").serialize(), function(data) {
		$('#paginated').html(data);
		ajaxOnComplete();
	});

}


function attachClipboardSWFs() {

	$(".clipboard-container").each(function() {
		var div = $(this); 
		var id = div.attr('id');
		var code = div.attr('code');
		id = id.replace('clipboard-container-', '');

		var url = $("#clipboard-link-"+id).attr("href");
		
		var clip = new ZeroClipboard.Client();	
		clip.setText(code);
		clip.setHandCursor( true );
		clip.glue('clipboard-subcontainer-'+id, 'clipboard-container-'+id); 

		var self = $(this);

		var cliplistener = {}; 
		cliplistener.click = function(e) {
			window.location = url; 
		}
		/* copied from main.js */
		cliplistener.mouseover = function(e) {
			var tooltip = self.parents("li").find(".tooltip-deal");
			$(tooltip).stop(true, true).delay(300).fadeIn(200);	
		}
		cliplistener.mouseout = function(e) {
			var tooltip = self.parents("li").find(".tooltip-deal");
			$(tooltip).stop(true, true).fadeOut(200);
		}
		/* --- */ 

		clip.addEventListener( 'onMouseDown', [cliplistener, 'click']);
		clip.addEventListener( 'onMouseOver', [cliplistener, 'mouseover']);
		clip.addEventListener( 'onMouseOut', [cliplistener, 'mouseout']);
		
	});
}



function favoriteTabError(isError) {
	if (isError) {
		$("#header-signin-overlay-incorrect-error").fadeIn();
		$("#coupon-tab-favourites-overlay-signin-title").hide();
		$("#coupon-tab-favourites-overlay-error").fadeIn();
	} else {
		$("#header-signin-overlay-incorrect-error").hide();
		$("#coupon-tab-favourites-overlay-signin-title").show();
		$("#coupon-tab-favourites-overlay-error").hide();
	}
}

function forgotTabError(isError) {	
	if (isError) {
		$("#header-signin-overlay-forgot-error").fadeIn();
		$("#header-signin-overlay-forgot-title").hide();
	} else {
		$("#header-signin-overlay-forgot-error").hide();
		$("#header-signin-overlay-forgot-title").show();
	}
}

function ajaxOnComplete() {
	
	//no longer need to "change views" between coupons and merchants
	//changeCouponView(COUPON_VIEW);
	
	//attachClipboardSWFs();

	//$(window).scrollTo(280, 500);
        $(window).scrollTo( $("#paginated"), 500); 
	$.modal.close();
	$(".prevent-close").click(function(e){
		e.stopPropagation();
	});
}

// This function allows you to call the fancy box from javascript
// origional source: http://outburst.jloop.com/2009/08/06/call-fancybox-from-flash/
function callBoxFancy(my_href) {
    document.getElementById("fancybox").href = my_href;
    $('#fancybox').trigger('click');
}

function open_coupon_dialogue(url){
    couponDialogue = window.open(url, null, "width=670,height=800,scrollbars=1,resizable=1,top=1,left=1");
    couponDialogue.focus();
}

function favoriteCoupon(cid, uid) {
    
    $.post("/users/ajaxfavorite/"+cid+"/coupon", '', function(data) {

            if (data == '1') {
                $('#couponSavedBox > h1').text("This coupon has now been saved.");
                callBoxFancy('#couponSavedBox');
            } else if (data == '0') {
                $('#couponSavedBox > h1').text("You have already saved this coupon");
                callBoxFancy('#couponSavedBox');
            }
    });
}

function like(fid, type){
    $.post("/users/ajaxlike/"+fid+"/"+type, '', function(data) {
        if (data == '1') {
            alert('Like success!!');
        } else if (data == '0') {
            alert('You\'ve already liked this '+type+'.');
        }
    });
}

function favoriteOther(id, type) {

	$.post("/users/ajaxfavorite/"+id+"/"+type, '', function(data) {

            if (data == '1') {
                $('#couponSavedBox > h1').text("This "+type+" has now been saved.");
                callBoxFancy('#couponSavedBox');
            } else if (data == '0') {
                $('#couponSavedBox > h1').text("You have already saved this "+type);
                callBoxFancy('#couponSavedBox');
            }

	}); 
}


/* Sam's stuff */

var subcategories='';
var merchants='';
$("#comma_list").val('');

function expand_subs(id){
	//$('.subcategories').hide('slow');
	$("#sub_cat_"+id).toggle('slow');
}

function populate_merchants(id){
	$("#merchant_holder p span").html('<img src="/img/throbber.gif" height="25" style="margin-top: 5px;" />');
	$("#merchants").html('');
	$("#coupons").html('');
	$("#merchants").load("/list/get_merchants/"+id, function(data){
		$("#subcategories option").each(function(){
			subcategories+=$(this).val()+',';
		});
		$("#merchants option").each(function(){
			merchants+=$(this).val()+',';
		});
		$("#merchant_holder p span").html('');
		populate_coupons(merchants, subcategories, 0);		
	});
}

function populate_subcategories(id){
	$("#subcategories").html('');
	$("#merchants").html('');
	$("#coupons").html('');
	$("#subcat_holder p span").html('<img src="/img/throbber.gif" height="25" style="margin-top: 5px;" />');
	$("#subcategories").load("/list/get_subcategories/"+id, function(data){ 
		$("#subcategories option").each(function(){
			$("#subcat_holder p span").html('');
			subcategories+=$(this).val()+',';
			$("#subcat_holder p span").html('');
			if ($("#coupons")){
				populate_coupons(0, subcategories, 0);
			}
		});
	});
}

function populate_coupons(merchant_id, cat_id, type_id){
	var excludes=',';
	$("#coupons").html('');
	$("#coupon_holder p span").html('<img src="/img/throbber.gif" height="25" style="margin-top: 5px;" />');
	$("#custom_list option").each(function(){ 
		excludes+=$(this).val()+','; 
	});
	$("#coupons").load("/list/get_coupons/"+merchant_id+"/"+cat_id+"/"+type_id+"/0/"+excludes, function(data){ 
		$("#coupon_holder p span").html('');
		subcategories='';
		merchants='';
	});
}

function populate_list(list_id){
	$("#load_list").html('<img src="/img/throbber.gif" height="25" style="margin-top: 5px;" />');
	$("#custom_list").load("/list/get_coupons/0/0/0/"+list_id+"/0", function(data){ 
		subcategories='';
		merchants='';
		$("#load_list").html('');
	});

}

function add(){
	html="<option value='"+$("#coupons option:selected").val()+"'>"+$("#coupons option:selected").html()+'</option>';
	if($("#coupons option:selected").html()){
		$("#coupons option:selected").remove();
		$("#custom_list").append(html);
	}
}

function add_to_list(id){
	val=$("#coupons option:selected").val();
	if(val){
		$.post("/list/add_to_list/"+id+"/"+val, function (data){
			$("#column").append(data);
		});
	}
}

function add_merchant_to_list(id){
	val=$("#merchants option:selected").val();
	if(val){
		$.post("/list/add_merchant_to_list/"+id+"/"+val, function (data){

                        var result = $.parseJSON(data);

                        if(result.success){
                            $("#related-merchants").append(result.html);
                        }
		});
	}
}

function add_product_group_to_list(list_id){
    var pg_id = $("#product_groups option:selected").val();
    
    if(pg_id){
        $.post("/list/add_product_group_to_list/"+list_id+"/"+pg_id, function (data){


                var result = $.parseJSON(data);

                if(result.success){
                    $("#related-product-groups").append(result.html);
                }
        });
    }
}

function add_product_to_group(group_id){
    var product_id = $("#allProducts option:selected").val();

    if(product_id){
        $.post("/admin/add_product_to_group/"+group_id+"/"+product_id, function(data){
            $("#products").append(data);
        });
    }
}

function remove(){
	html="<option value='"+$("#custom_list option:selected").val()+"'>"+$("#custom_list option:selected").html()+'</option>';
	if ($("#custom_list option:selected").html()){
		$("#custom_list option:selected").remove();
		$("#coupons").append(html);
	}
}


function process_list(){
	$("#custom_list option").each(function(){ 
		$("#comma_list").val($("#comma_list").val()+","+$(this).val()); 
	});
	return true;
}

function load_list(){
	$("#list_name").val($("#list_id option:selected").html());
	populate_list($("#list_id").val());
}

function vote(coupon_id, user_id, vote, toolbar){
	data="data[Vote][user_id]="+user_id;
	data+="&data[Vote][coupon_id]="+coupon_id;
	data+="&data[Vote][vote]="+vote;
	data+="&data[Vote][comment_text]="+$("input[name='rating-overlay-reason']").val();
	data+="&data[Vote][comment_type_id]="+$("input[name='rating-overlay']:checked").val();
	
	$.post("/coupons/works", data, function(data) { 
		//close overlay
		dislikeTab(-1);
		//$("#notwork_form_"+coupon_id).hide('fast');
		//$("div#vote_"+coupon_id).html(data); 
		
		if (data == 0) {
			alert("You have already rated this coupon.");		
		} else if (data == -1) {
			alert("Sorry, there was an error rating this coupon.");				
		} else {
			if (toolbar == undefined || !toolbar) {
				//update percentage 
				$("#coupon-bottom-rating-id-"+coupon_id).hide().fadeIn(); 
				$("#coupon-bottom-rating-id-"+coupon_id).html(data);			
			} else {
				
				$("#yes").hide().fadeIn('slow'); 
			}
		}
	});
	return false;
}

function showComments(id){
	$("#current_comments_"+id).html('<img src="/img/throbber.gif />');
	$("#current_comments_"+id).load("/coupons/get_comments/"+id, function(data){});
	$("#comment_"+id).toggle();
	
	return false;
}

function save_comment(id){
	data="data[Comment][user_id]="+$("#comment_user_"+id).val();
	data+="&data[Comment][coupon_id]="+$("#comment_coupon_"+id).val();
	data+="&data[Comment][parent_id]="+$("#comment_parent_"+id).val();
	data+="&data[Comment][comment]="+$("#comment_text_"+id).val();
	$.post("/coupons/comment", data, function(data) {
		//$("#comment_form_"+id).hide(); 
		$("#comment_text_"+id).val(''); 
		$("#current_comments_"+id).append(data);
		count=parseInt($("#comment_icon_count_"+id).html());
		if (!count){
			count=0;
		}
		count++;
		$("#comment_icon_count_"+id).html(count);
		$("#comment_count_"+id).html(count+" Comment"+(count > 1 || count==0 ? 's' : ''));
		
	});
	return false;
}

function send_email(id, type){

	$.post("/coupons/send_mail/"+type+'/'+id, $("#shareByEmailForm-"+type+'-'+id).serialize(), function(data) {

            var result = $.parseJSON(data);

            if(result.success){
                $("#shareByEmailForm-"+type+'-'+id).prepend('Message has been sent!');
            }

	});
	return false;
}

function comment_vote(comment_id, user_id){
	data="data[CommentVote][comment_id]="+comment_id;
	data+="&data[CommentVote][user_id]="+user_id;
	$.post("/coupons/comment_vote/", data, function(data) {
		$("#comment_vote_"+comment_id).html(parseInt($("#comment_vote_"+comment_id).html())+parseInt(data));
		alert(parseInt(data) ? "Thanks for voting!" : "You've already voted on this.");
	});
}


function admin_coupon_delete(id, admin_code, state){
	var answer = confirm("Are you sure you want to "+(state ? "restore" : "delete")+" this coupon?");
	if (answer){
		$.post("/admin/delete_coupon/"+id+"/"+admin_code+"/"+state, function(data){
			//alert(data);
			if(data==1){
                               if($('.coupon-list').length){
                                   $('#coupon-admin-'+id).parent().hide('slow');
                               } else if($('#active-coupons').length){
                                   $('#coupon-'+id).hide('slow');
                               }
			}
		});
	}
	else{}
	return false;	
}

function remove_from_list(id, coupon){
	var answer = confirm("Are you sure you want to remove this coupon?");
	if (answer){
		$.post("/admin/delete_from_list/"+id+"/"+coupon, function(data){
			$("#list_coupon_"+coupon).remove();
		});
	}
	else{}
	return false;	
}

function remove_merchant_from_list(id, merchant){
    var answer = confirm("Are you sure you want to remove this merchant?");
    if (answer){
            $.post("/admin/delete_merchant_from_list/"+id+"/"+merchant, function(data){
                if(data==0){
                    $("#list_merchant_"+merchant).remove();
                }
            });
    }
    return false;
}

function remove_product_group_from_list(list_id, group_id){
    var answer = confirm("Are you sure you want to remove this product group?");
    if (answer){
            $.post("/admin/delete_product_group_from_list/"+list_id+"/"+group_id, function(data){

                if(data==0){
                    $("#list_product_group_"+group_id).remove();

                }
            });
    }
    return false;
}

function add_to_hot(id, type){
	$.post("/admin/add_trend/"+id+"/"+type, function(data){
		alert(data);
	});
	return false;
}

function remove_trend(id){
	$.post("/admin/remove_trend/"+id, function(data){
		$("#trend_"+id).hide("slow");
	});
	return false;
}

function unfavorite(type, id){
	
	if(type=="coupon"){
		obj=$("#coupon-id-"+id+" .coupon-tab-favourites-active");
		counter=$("#coupon-id-"+id+" .coupon-tab-favourites-active .coupon-badge-middle");
		obj.addClass('coupon-tab-favourites');
		obj.removeClass('coupon-tab-favourites-active');
	}
	else if(type=="list"){
		obj=$("#list-id-"+id+" .coupon-tab-favourites-active");
		counter=$("#list-id-"+id+" .coupon-tab-favourites-active .coupon-badge-middle");	
		obj.addClass('coupon-tab-favourites');
		obj.removeClass('coupon-tab-favourites-active');
	}

	if(type=="merchant") {
		obj=$('#browse-header-merchant-'+id+' .browse-header-favourite-active');
		counter=$("#browse-header-merchant-"+id+" .browse-badge-middle");
		obj.addClass('browse-header-favourite');
		obj.removeClass('browse-header-favourite-active');

	} else {
		//search, category, cp_category
       obj=$("#browse-header-default .browse-header-favourite-active");
       counter=$("#browse-header-default .browse-header-favourite-active .browse-badge-middle");
       obj.addClass('browse-header-favourite');
       obj.removeClass('browse-header-favourite-active');
	}
			
	//fav_count=parseInt(counter.html())-1;
	$.get("/users/unfavorite/"+type+"/"+id, function(data){
		counter.html(data);	
	});
	return false;
}

function unfave(obj, id, type){
   count=parseInt($("span#uf_"+type+"_count").html())-1;
   $.get("/users/unfavorite/"+type+"/"+id, function(data){
           obj.parents("li").remove();
           if(data!="blacklist"){
               $("span#uf_"+type+"_count").html(count);
           }

   });
   return false;
}

function delete_comment(id){
	$.get("/admin/delete_comment/"+id, function(data){
		$("#comment-id-"+id).remove();
	});
	return false;
}
	
function highlight_comment(id){
	$.get("/admin/highlight_comment/"+id, function(data){
		$("#highlight-comment-id-"+id).html(data==0 ? "Feature" : "Unfeature");
	});
	return false;
}

function contact_us(){
	postdata="data[name]="+$("#contact-form-input-name input").val();
	postdata+="&data[email]="+$("#contact-form-input-email input").val();
	postdata+="&data[message]="+$("textarea#contact-form-input-message").val();
	$.post("/coupons/contact", postdata, function(data){
		$("#contact-form").html("Your message has been sent. We will respond to it as soon as we can.");	
	});
	return false;
}

/***********************************************
* Bookmark site script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

function bookmarksite(title,url){
    if (window.sidebar) {
        // firefox
        window.sidebar.addPanel(title, url, "");
    }
    else if(window.opera && window.print) { // opera
            var elem = document.createElement('a');
            elem.setAttribute('href',url);
            elem.setAttribute('title',title);
            elem.setAttribute('rel','sidebar');
            elem.click();
    }
    else if(document.all) {// ie
            window.external.AddFavorite(url, title);
    }
}
	
	
/**
 *
 * jquery.charcounter.js version 1.2
 * requires jQuery version 1.2 or higher
 * Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
 
(function($) {
	/**
	 * attaches a character counter to each textarea element in the jQuery object
	 * usage: $("#myTextArea").charCounter(max, settings);
	 */
	
	$.fn.charCounter = function (max, settings) {
		max = max || 100;
		settings = $.extend({
			container: "<span></span>",
			classname: "charcounter",
			format: "(%1 characters remaining)",
			pulse: true,
			delay: 0
		}, settings);
		var p, timeout;
		
		function count(el, container) {
			el = $(el);
			if (el.val().length > max) {
			    el.val(el.val().substring(0, max));
			    if (settings.pulse && !p) {
			    	pulse(container, true);
			    };
			};
			if (settings.delay > 0) {
				if (timeout) {
					window.clearTimeout(timeout);
				}
				timeout = window.setTimeout(function () {
					container.html(settings.format.replace(/%1/, (max - el.val().length)));
				}, settings.delay);
			} else {
				container.html(settings.format.replace(/%1/, (max - el.val().length)));
			}
		};
		
		function pulse(el, again) {
			if (p) {
				window.clearTimeout(p);
				p = null;
			};
			el.animate({ opacity: 0.1 }, 100, function () {
				$(this).animate({ opacity: 1.0 }, 100);
			});
			if (again) {
				p = window.setTimeout(function () { pulse(el) }, 200);
			};
		};
		
		return this.each(function () {
			var container;
			if (!settings.container.match(/^<.+>$/)) {
				// use existing element to hold counter message
				container = $(settings.container);
			} else {
				// append element to hold counter message (clean up old element first)
				$(this).next("." + settings.classname).remove();
				container = $(settings.container)
								.insertAfter(this)
								.addClass(settings.classname);
			}
			$(this)
				.unbind(".charCounter")
				.bind("keydown.charCounter", function () { count(this, container); })
				.bind("keypress.charCounter", function () { count(this, container); })
				.bind("keyup.charCounter", function () { count(this, container); })
				.bind("focus.charCounter", function () { count(this, container); })
				.bind("mouseover.charCounter", function () { count(this, container); })
				.bind("mouseout.charCounter", function () { count(this, container); })
				.bind("paste.charCounter", function () { 
					var me = this;
					setTimeout(function () { count(me, container); }, 10);
				});
			if (this.addEventListener) {
				this.addEventListener('input', function () { count(this, container); }, false);
			};
			count(this, container);
		});
	};
        

})(jQuery);

