$(function() {
  
  // this is for IE
  if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (obj, fromIndex) {
      if (fromIndex == null) {
        fromIndex = 0;
      } else if (fromIndex < 0) {
        fromIndex = Math.max(0, this.length + fromIndex);
      }
      for (var i = fromIndex, j = this.length; i < j; i++) {
        if (this[i] === obj)
        return i;
      }
      return -1;
    };
  }
	
 
	$("a.close-notification").click(function() {
		$.post(this.href, { announcement_id: this.id.split("-")[1] })
		$(this).parent().fadeOut();
		return false;
	})

	$("a.show_upload").click(function() {
		$(this).hide();
		$("#header_upload").show();
		return false
	})
	$(".import").click(function() {
		$(this).hide();
		$("#search-progress").show();
	})

	$("a.remove-list-followup").click(function() {
		var el = $(this).parent("div.page-select")
		$.get(this.href, function(data) {
			switch(data) {
				case 'success':
					el.hide('slow', function(){ el.remove(); });
					break;
				case 'nolist':
				  el.hide('slow', function(){ el.remove(); })
				  $("label#for-existing-lists").fadeOut();
					break;
				case 'failure':
				  alert("Error: Failed to delete list!");
					break;
			}
		})
		return false;
	})

	$("a.add-page-to-list").click(function() {
		$("div.page-select:last").clone(true).insertAfter("div.page-select:last")
			.css("margin-top", "5px").children("p, label").remove();
		return false;
	});

	$("input#select-all-contacts").click(function() {
		$("input.to-delete").attr('checked', this.checked)
	});

	$("a.delete-page").click(function() {
		$(this).parent("div.page-select").remove();
	})

	$("a#add-another-contact").click(function() {
		last_instance = $("div.add-contacts:last")
		new_element = last_instance.clone(true);
		input = new_element.find("input[type='text']")
		input.each(function() {
			this.name = this.name.replace(/\d/, new Date().getTime())
		})
		new_element.insertAfter("div.add-contacts:last").css("margin-top", "0px")
		$("div.add-contacts:last").find("input").val("")
		$("div.add-contacts:last label").remove()
		return false;
	})

	$("select#contact_action").change(function() {
		switch(this.options[this.selectedIndex].value) {
			case "0":
				return false;
			case "delete":
				checked = $("input.to-delete:checked");
				if(checked.length == 0) {
					alert("Please select some contacts..")
					$(this).val('0')
					return false;
				}
				result = confirm("Are you sure you want to delete " + checked.length + " contact(s)?")
				if(!result) {
					$(this).val('0')
					return false;
				} else {
					$('form#action-form').submit();
				}
		}
	});

	$("input#page_location").keyup(function() {
		$("p#custom-location").text($(this).val())
	})

/*	$("#upload-logo").click(function() {
		alert(("#logo_uploaded_data").length)
		if(("#logo_uploaded_data").val() == "")
			return false
	})*/

	if($("div.flash").length > 0) {
	 show_flash();
	}
	$("div.flash").live('click', function() {$(this).slideUp()})


	$("#remove_video").click(function() {
		$("div.video_box").empty().load("/pages/remove_video",
			{id: $("input#page_id").val(), authenticity_token: window._token},
			function() { video_toggle()}
		)
	})

	$(".popupClose").click(function(){
		disablePopup();
	});
	//Click out event!
	$("#backgroundPopup").click(function(){
		disablePopup();
	});
	//Press Escape event!
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup();
		}
	});

	$("a#add_cc").click(function() {
		$(this).hide();
		$("div.cc_bcc").show();
		$("a#no_cc").show();
	})
	$("a#no_cc").click(function() {
		$(this).hide();
		$("div.cc_bcc").hide();
		$("a#add_cc").show();
	})

	var referrer = document.referrer
	if(!referrer.match(/(\w+\.)?flowtown\.com/)) {
		var code = getUrlVars()['code']
		if(!$.cookie('code') && code)
			$.cookie('code', code, {expires: 360,path: '/',domain: '.'+document.domain.match(/(\w+\.\w+)$/)[0]})	
		if(!$.cookie('referer'))
			$.cookie('referer', referrer, {expires: 360,path: '/',domain: '.'+document.domain.match(/(\w+\.\w+)$/)[0]})
	}

    $(".enable-api").click(function() {
        var account_id = $(this).attr("data-account-id");
        var url = $(this).attr("data-url");
        var api_enabled = $(this).attr("checked");
        $.post(url, {authenticity_token: FORM_AUTH_TOKEN,
                                       account_id: account_id,
                                       api_enabled: api_enabled},
                                       function(data) {
            $("div.flash").remove();
            $("div.wrapper").append(data);
            show_flash();
        })
    })
})

function show_flash() {
	 $("div.flash").slideDown();
		setTimeout(function(){$("div.flash").slideUp()}, 10000);
}

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            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
        }
        // NOTE 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;
    }
};

function highlight(field) {
	field.focus();
	field.select();
}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function include(arr,obj) {
  return (arr.indexOf(obj) != -1);
}

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

jQuery.fn.submitWithAjax = function() {
  this.submit(function() {
    sLoad();
    $(this).find("input[type='submit']").attr("disabled", "disabled");
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
  })
  return this;
};
