
$(document).ready(function() {
    page_ctx = context;
    setup_category_menu();
    setup_live_search();
    setup_form_features();
    setup_tally_features();
    setup_adminterface();
    switch(document.body.id) {
    case 'product_info':
      setup_product_page();
      break;
    case 'discussion':
      setup_discussion_page();
      break;
    case 'dash':
      setup_dashboard_page();
      break;
    case 'dashboard_merchant':
      setup_dashboard_merchant_page();
      break;
    case 'dashboard_market':
      setup_dashboard_market_page();
      break;
    case 'market_listing':
      setup_marketplace_listing_page();
      break;
    case 'member_profile':
      setup_member_profile_page();
      break;
    case 'signup':
      setup_signup_page();
      break;
    }

    $('a.tips').cluetip();
    if ($(window).height() > $(document).height()) {
      $('#bd').css({
	height: $('#bd').height() +
		       ($(window).height() -
			$(document).height()) + 'px'
	});
    }

    $('#recommend_bar').hide();
    $('#recommend_lnk').click(function(e) {
        e.preventDefault();
        $('#recommend_bar').show();
    });

});

setup_adminterface = function() {

    if ($('#admin_interface').length) {
	var coordinates = $('#admin_interface').offset();
	var menu = $('#admin_interface > ol');
	menu
	.hide()
	.appendTo($(document.body))
	.css('position', 'absolute')
	.css('top', coordinates.top + 10)
	.css('left', coordinates.left)
	.css('border', '3px solid #578bc5')
	.hover(function(){}, function(){$(this).hide();});

	$('li', menu).css('background', 'white');

	$('#admin_interface').hover(
	  function() {menu.show();},
	  function() {}
	);
    }
};

setup_signup_page = function() {

    $("#popup_privacy").click(function(e) {
        e.preventDefault();
        window.open("/main/privacy", '', 'width=850,height=625,status=yes,resizable=yes,scrollbars=yes');
    });

    $("#popup_terms").click(function(e) {
        e.preventDefault();
        window.open("/main/terms", '', 'width=850,height=625,status=yes,resizable=yes,scrollbars=yes');
    });

};

setup_category_menu = function(){
    var coordinates = $('#retail').offset();
    $("#retail_menu")
      .hide()
      .appendTo($(document.body))
      .css('position', 'absolute')
      .css('top', coordinates.top)
      .css('left', coordinates.left);
    $("#retail").hover(
        function(){ $('#retail_menu').show(); },
        function(){ }
    );

    $("#retail_menu").hover(
	function(){ },
	function(){ $(this).hide(); }
    );

    if (document.all) {
        $("#retail_menu li").hoverClass("sfHover");
    }
};

$.fn.hoverClass = function(c) {
    return this.each(function(){
        $(this).hover(
            function() { $(this).addClass(c);  },
            function() { $(this).removeClass(c); }
        );
    });
};

setup_live_search = function() {
    var ls = $('#liveinput');
    var coordinates = ls.offset();
    $("#live_results")
      .hide()
      .appendTo($(document.body))
      .css('position', 'absolute')
      .css('top', coordinates.top + 25)
      .css('left', coordinates.left);

    var check_live_search = function() {
	live_search_value = ls.val();
	if(old_search_value != live_search_value) {
	    $('#live_results')
	      .load('/ajax/products/live_search_ajah',
		    {search_so_far: live_search_value})
	      .show();
	}
	old_search_value = live_search_value;
	$('#live_results li')
          .css('cursor', 'pointer')
	  .each(function(){
	      $(this).click(function(){window.location.href = $('a:first', this).attr('href'); return false;});
	});
    };

  ls.focus(function(){$('#live_results').show();});
    $('#live_results').hover(
	function(){$('#live_results').show();},
	function(){$('#live_results').hide();});

    old_search_value = ls.val();
    setInterval(check_live_search, 500);

};

setup_product_page = function() {

    //Setup map
    if (GBrowserIsCompatible() && page_ctx) {

        var map = new GMap2(document.getElementById("map"));

        map.enableContinuousZoom();

        var stores = page_ctx.store_map.stores;
        var user_lat = page_ctx.store_map.latitude;
        var user_lon = page_ctx.store_map.longitude;

        var points = [];

        map.setCenter(new GLatLng(user_lat, user_lon), 10);

        $.each(stores, function(index, store){
	  if(store.latitude && store.longitude) {
            var point = new GLatLng(store.latitude, store.longitude);

            var cIcon = new GIcon(G_DEFAULT_ICON);

            if(store.status == 'instock') {
              cIcon.image = '/images/map_icons/' + store.icon.split('/')[3].split('.')[0] + '-gmap-pin.png';
            } else {
              cIcon.image = '/images/retail_search_icon.png';
            }
              var markerOpt = {icon: cIcon};
              var marker = new GMarker(point, markerOpt);
              map.addOverlay(marker);
          }
        });
    }

    // Set up map
    //$('#map').jmap('init', {mapCenter:[40.755319574776024, -73.99738311767578]});

    // Wishlist Choice Form
    $('#wishlist_choices').hide();

    // Set up tabs
    $('#description_specifications > ul').tabs({ fx: { height: 'toggle', opacity: 'toggle', duration: 500 } });
    $('#store_map > ul')
      .tabs({ fx: { height: 'toggle', opacity: 'toggle', duration: 500 } })
      .tabs('add', '/retail/offers?asin='+ page_ctx['asin'], 'Online Offers');

    // Simulate click on third tab!
    $('#marketdiv').click(function() {
        $('#store_map > ul').tabs('select', 2);
    });

    // Set up tablesorter
    $('#market_table').tablesorter({ widgets: ['zebra'] });
    $('#market_table tr').click(function() {
        location.href = '/market/listing/' + this.id;
     });

    // Set up toggle UI for location
    $('.pricing_store')
        .css('cursor', 'pointer')
        .click(function(event) {
	    $(this).children().filter('table')
	        .slideToggle('slow');
	    event.preventDefault();
	})
        .children().filter('table').css('display', 'none');

    // JSONify user review links
    $('.useful').click(function(event) {
        event.preventDefault();
        var r_url = this.href;
        var r_id = this.id;
        $.getJSON(r_url, function(json) {
            if (json.is_usr == false) {
                $('html, body').animate({scrollTop: 0}, 'fast');
                $('#flash')
                   .text(json.error)
                   .css({backgroundColor:'#b54335', color:'#1b3c5e'});
            } else {
               $('.y[@id='+r_id+']').text(json.helpful.y);
               $('.total[@id='+r_id+']').text(json.helpful.y+json.helpful.n);
            }
        });
    });
    $('.flag').click(function(event) {
        event.preventDefault();
        var f_url = this.href;
        var f_id = this.id;
        var img_src = '/images/flag_red.png';
        $.getJSON(f_url, function(json) {
            if (json.is_usr == false) {
                $('html, body').animate({scrollTop: 0}, 'fast');
                $('#flash')
                   .text(json.error)
                   .css({backgroundColor:'#b54335', color:'#1b3c5e'});
            } else {
                $('div[@id='+f_id+']')
                  .children().filter('.flagged')
                  .text(json.flag.msg);
                $('img[@id='+f_id+']').attr({src:img_src});
                $('.review[@id='+f_id+']').remove();
            }
        });
    });

    var pro_form = $('#pro_div');
    pro_form.fadeOut();
    var pro_signup = $('#pro_signup');
    pro_signup.fadeOut();

    $('#prolnk').click(function(e) {
        e.preventDefault();
        var p_url = this.href;
        $.getJSON(p_url, function(json) {
            switch(json.is_usr) {
                case false:
                    $('html, body').animate({scrollTop: 0}, 'fast');
                    $('#flash')
                       .text(json.error)
                       .css({backgroundColor:'#b54335', color:'#1b3c5e'});
                    break;
                case true:
                    pro_signup.toggle('slow');
                    break;
                case 'pro':
                    pro_form.toggle('slow');
                    break;
            }
        });
    });
    $('.close_pro').click(function(e){
        e.preventDefault();
        pro_form.hide('slow');
        pro_signup.hide('slow');
    });

    // Tiger striping
   $('table.matchit tr:even').addClass('custom_stripe_odd');
   $('table.matchit tr:odd').addClass('custom_stripe_even');

   $('table.offers tr:even').addClass('custom_stripe_odd');
   $('table.offers tr:odd').addClass('custom_stripe_even');

    // Star rating
    $('#usr_review_form :radio').rating();
    $('#pro_review_form :radio').rating();

    //var star_rating = $('#star_rating');
    //star_rating.hide();
    //
    //$('#rate_it').click(function(e) {
    //     e.preventDefault();
    //     star_rating.show();
    // });
    //
    //$('#rate_close').click(function(e) {
    //     e.preventDefault();
    //     star_rating.hide();
    // });

};

setup_discussion_page = function() {
    $('#wishlist_choices').hide();

    // Set up tabs
    $('#description_specifications > ul').tabs();

    // Set up toggle UI for location
    $('.pricing_store')
      .css('cursor', 'pointer')
      .click(function(event) {
        $(this).children().filter('table')
          .slideToggle('slow');
        event.preventDefault();
      })
        .children().filter('table').css('display', 'none');

   $('table.associations tr:even').addClass('assoc_odd');
   $('table.associations tr:odd').addClass('assoc_even');

};

setup_dashboard_page = function() {
  function set_search_results(response, status) {
    $('#wishlist_search_results').html(response);
  }

  $('#wishlist_search').ajaxForm({success:set_search_results});

  $('#wishlist_options_form').ajaxForm(
    {success: function(response, status) {
       $('#show_wishlist').html(response);
     },
     url: '/dashboard/wishlist'
   });

  $('#wishlist_options_form>input[@type="submit"]').hide();
  $('#wishlist_options_form>select').change(function() {
    $('#wishlist_options_form').submit();
  });

  $('.share_wishlist_form').livequery(function() {
    simple_ajaxify($(this));
  });

  // Tiger stripes
  $('ul>li:odd').addClass('odd');
  $('ul>li:even').addClass('even');

    // Ajaxitize and toggle messages
    var plus = '/images/bullet_toggle_plus.png';
    var minus = '/images/bullet_toggle_minus.png';

    $('.msg_txt').hide();
    $('.msglnk').click(function(event) {
        event.preventDefault();
        $('div[@id='+this.id+']')
            .load(this.href)
            .toggle();
        $('a[@id='+this.id+']')
            .find('.is_read')
            .css({'font-weight':'normal'});
    }).bind('click', function() {
        var m_img = $('.imgtoggle[@id='+this.id+']');
        if (m_img.attr('src') == minus) {
            m_img.attr({'src':plus});
        } else {
            m_img.attr({'src':minus});
        }
    });
    $('.delete').click(function(event) {
        event.preventDefault();
        $.get(this.href);
        $('tr[@id='+this.id+']').remove();
    });

    // Toggle store selection view
    $('#storelist').hide();
    $('#storelnk').click(function(event) {
        event.preventDefault();
        $('#storelist').slideToggle('slow');
    }).bind('click', function() {
        var s_img = $('#storetoggle');
        if (s_img.attr('src') == minus) {
            s_img.attr({'src':plus});
        } else {
            s_img.attr({'src':minus});
        }
    });

    // Messages select / deselect
    $('.chkselect').click(function(event) {
        event.preventDefault();
        var a_id = this.id;
        if (a_id == 'all') {
            $('input[@id=chk]').attr('checked', true);
        }
        else if (a_id == 'none') {
            $('input[@id=chk]').attr('checked', false);
        }
    });

    // Deselect all checkboxes
    $('#deselectall').attr('checked', true);
    $('#deselectall').click(function(event) {
        $('input[@id=chk]').attr('checked', this.checked);
    });

    // Survey
    var purchased = $('#purchased_section');
    var other_store = $('#other_store_section');
    other_store.hide();

    $('input[@name=bought]').change(function() {
        if ($(this).val() == 'no') {
            purchased.hide();
        } else {
            purchased.show();
        }
    });

    var stores = $('#tracked_stores');

    stores.change(function() {
        if (stores.val() == 'other') {
            other_store.show();
        } else {
            other_store.hide();
        }
    });
};

setup_dashboard_merchant_page = function() {

    var search_box = $('#search_box');
    search_box.hide();

    var live_search = $('#live_search_results');
    var product_search = $('#product_listing_search');

    // Hide custom listing form until activated
    var custom_form = $('#custom_listing_form');
    custom_form.hide();

    // Position image upload form.
    var picture_upload_position = $('#picture_upload_container').position();
    $('#image_upload_form').css(picture_upload_position);
    var upload_container_css = {'min-height': $('#image_upload_form').outerHeight() + 'px'};
    $('#picture_upload_container').css(upload_container_css);

    var regular_search = function() {
	var interaction = $('#step_find .step_interaction');

        custom_form.hide();
        product_search.show();
        live_search.show();

	$('#previous_search_method_link')
	  .unbind()
	  .empty();
	$('#step1_help_text').html('Here are some useful tips.');
	$('#next_search_method')
	  .html("Can't find it here? Try <a href=\"#\">Extended Search</a>")
          .children().filter('a')
          .css({'color':'#578bc5'})
          .unbind()
	  .click(extended_search);

	live_list('#product_listing_search', '#live_search_results',
		  '/ajax/products/live_product_list',
		  function(asin) {
		      setup_selection(asin);
		  });

	return false;
    };

    var extended_search = function() {
	var interaction = $('#step_find .step_interaction');

        custom_form.hide();
        product_search.show();
        live_search.show();

	$('#previous_search_method_link')
	  .html('Back to iTrackr Search')
          .css({'color':'#578bc5'})
	  .attr('href', '#')
   	  .unbind()
	  .click(function() {regular_search();});
	$('#step1_help_text').html('Extended search can find more products, but less iTrackr members will notice your listing.');
	$('#next_search_method')
            // Disable custom listing feature for now, no way to browse or search for one!
            //.html("Can't find it here?<br />Try a <a>Custom Listing</a>")
            .empty()
            .children().filter('a')
            .css({'color':'#578bc5'})
            .unbind()
            .click(custom_listing);

	live_list('#product_listing_search', '#live_search_results',
		  '/ajax/products/extended_search',
		  function(asin) {
		      setup_selection(asin);
		  });

	return false;
    };

    var custom_listing = function() {
        var interaction = $('#step_find .step_interaction');

        custom_form.show();
        product_search.hide();
        live_search.hide();

        $('#previous_search_method_link')
            .html('Back to Extended Search')
            .css({'color':'#578bc5'})
            .unbind()
            .click(function() {
                extended_search();
            });
        $('#step1_help_text').html('Custom listings cannot be tracked and could be difficult for iTrackr members to find.');
        $('#next_search_method').empty();
    };

    // By default, use regular_search
    regular_search();

    $('a.remove').livequery(function() {
	$(this).click(function(e) {
	    var for_image = $(this).attr('for_image');
            e.preventDefault();
            $('*[for_image='+for_image+']').remove();
	});
    });

    // Set up image upload options
    var img_form_options = {

        success: function(json) {

            var usr_pics = $('#picture_selection');

            // Append user-added images
            $('<img class="user_added"/>')
	      .attr('src', json.url)
	      .attr('for_image', json.hash)
	      .appendTo(usr_pics);

            $('<input type="hidden" name="user_image" />')
	      .attr('value', json.url)
	      .attr('for_image', json.hash)
	      .appendTo(usr_pics);

            $('<a href="#" class="remove" title="remove this image">[x]</a>')
	      .attr('for_image', json.hash)
	      .appendTo(usr_pics);

        },

        dataType: 'json',
        clearForm: true,
        resetForm: true
    };

    // Set up merchant form options
    var merchant_form_options = {
        success: function(json) {

            $('.error').empty();

            if (json.success == true) {
                location.href = json.url;
            } else {
                if (json.error.asin) {
                    $('#search_so_far_error').text(json.error.asin);
                }
                if (json.error.condition) {
                    $('#condition_error').text(json.error.condition);
                }
                if (json.error.price) {
                    $('#price_error').text(json.error.price);
                }
                if (json.error.contact_email) {
                    $('#contact_email_error').text(json.error.contact_email);
                }
                if (json.error.contact_phone) {
                    $('#contact_phone_error').text(json.error.contact_phone);
                }
                if (json.error.contact_required) {
                    $('#contact_required_error').text(json.error.contact_required);
                }
                if (json.error.contact_im_toggle) {
                    $('#contact_im_toggle_error').text(json.error.contact_im_toggle);
                }
            }

        },
        dataType: 'json'
    };

    // Bind forms using 'ajaxForm'
    $('#image_upload_form').ajaxForm(img_form_options);
    $('#merchant_form').ajaxForm(merchant_form_options);

    // Set up the condition selections.
    var used_more = $('#used_more');
    var new_more = $('#new_more');
    var cond_detail_field = $('#cond_detail_field');

    used_more.hide();
    cond_detail_field.hide();

    $('#condition_select').change(function() {
      switch($(this).val()) {
      case 'new':
        new_more.show();
        used_more.hide();
        cond_detail_field.hide();
        break;
      case 'used':
        if (used_more.val() == 'broke') {
          cond_detail_field.show();
          cond_detail_field.focus();
        } else {
          cond_detail_field.hide();
        }
        used_more.change(function() {
	  if (used_more.val() == 'broke') {
	    cond_detail_field.show();
	    cond_detail_field.focus();
	  } else {
	    cond_detail_field.hide();
	  }
	});
        used_more.show();
        new_more.hide();
        break;
      case 'custom':
        used_more.hide();
        new_more.hide();
        cond_detail_field.show();
        cond_detail_field.focus();
        break;
      }
    });

    // Disable name and description fields
    $('#name_field').attr('disabled', 'disable');
    $('#description_field').attr('disabled', 'disable');

    var setup_selection = function(asin) {
	// Set images
	$.getJSON('/ajax/products/product_details', {asin:asin}, function(json) {
	    //Clear the product images, then add the correct ones.
	    picture_list = $('#picture_selection');
	    picture_list.find('.auto_added').remove();
	    $.each(json.urls, function() {
		$('<img class="auto_added"/>').attr('src', this).appendTo(picture_list);
                $('#asin').attr('value', asin);
	    });

	    $('#name_field').val(json.name);
	    $('#you_are_selling').html('You are selling <span id="product_name">' + json.name + '</span>');
	    $('#find_product_link').html('Change this').attr('title', 'Try your search again');
	    $('#description_field').html(json.description);

	    //Display the categories from the chosen product vs selecting one.
	    $('#category>label').hide();
	    $('#category>p.auto_category').remove();
	    $.each(json.categories, function() {
		cat = this + '';
		$('<p class="auto_category"/>').text(cat).appendTo($('#category'));
	    });

	});
	// Exit modal.
	tb_remove();
    };

    var im_options = $('#im_options');
    im_options.hide();

    // Disable the search field while in edit mode.
    var is_edit = $('#is_edit');

    // Hide specific IM types until IM is turned on
    // Toggle im options only if not in edit-mode
    var im_toggle = $('input[name=contact_im_toggle]');
    var aim_toggle = $('input[name=contact_aim_toggle]');

    if (is_edit.attr('value') == 'no') {
        im_toggle.click(function() {
            //e.preventDefault();
            im_options.toggle();
        });

        $('.im').click(function() {

/*            var ims = []

            $('.im').each(function() {
                ims.push($('#skype').val());
                alert($('#skype').val());
            });          */

            //$.each(ims, function(index, im) {
            //    alert(im);
            //    if (im == true) {
            //        alert('hi');
            //    } else if (im == false) {
            //        alert('boo');
            //    }
            //});

            //var array = $('.im:checked').serializeArray();
            //alert(array[0]);
        });
    }

    // Specific options while in edit-mode
    if (is_edit.attr('value') != 'no') {
        $('#product_listing_search')
            .attr('disabled', 'disable');
        if ($('#condition_select').val() == 'used') {
            new_more.hide();
            used_more.show();
        }
        if ($('#condition_select').val() == 'custom') {
            new_more.hide();
            used_more.hide();
            cond_details.show();
        }
        if ($('#used_more').val() == 'broke') {
            cond_details.show();
        }
        $('input[name=contact_im_toggle]').click(function() {
            im_options.show();
        });
    }

    var contact_email = $('input[@name=contact_email]');
    var paypal_email = $('input[@name=paypal_email]');
    var paypal_same = $('input[@name=paypal_same]');

    paypal_same.click(function() {
        if (this.checked) {
            paypal_email.attr('value', contact_email.val());
        }
    });

    contact_email.keyup(function() {
        paypal_same.attr('checked', false);
    });

    paypal_email.keyup(function() {
        paypal_same.attr('checked', false);
    });

};

setup_dashboard_market_page = function() {

    $('.icon_a').lightbox();

    $('.icon').hover(function() {
        $('#listing_img'+this.id).attr('src', '/live_images/bound/140/140/'+this.name);
    });

};

setup_marketplace_listing_page = function() {

    $('#gallery a').lightbox();

    $('.img_thumb').hover(
        function() {
            $(this).css({borderColor:'black', background:'#efefef'});
            $('#listing_image')
	      .attr('src', '/live_images/product_info_large/'+this.id);
        },
        function() {
            $(this).css({borderColor:'#ccc', background:'white'});
    });

    //$('#marketplace_interact_form').ajaxForm({
    //    success: function(resp) {
    //        if(resp) {
    //            $('#interact_append').html(resp)
    //            $('#marketlistingform').hide();
    //        }
    //        else {
    //            $('html, body').animate({scrollTop: 0}, 'fast');
    //            $('#flash').text(json.error);
    //            $('#marketlistingform').hide();
    //        }
    //    },
    //    clearForm: true,
    //    resetForm: true
    //});

};

setup_member_profile_page = function() {

    // Set up messaging options
    var options = {

        success: function(json, status) {
            if (json.success == false) {
                if (json.type == 'no_msg') {
                    $('html, body').animate({scrollTop: 0}, 'fast');
                    $('#flash')
                        .text(json.error)
                        .css({backgroundColor:'#b54335', color:'#1b3c5e'});
                } else if (json.type == 'no_contact') {
                    $('html, body').animate({scrollTop: 0}, 'fast');
                    $('#flash')
                        .text(json.error)
                        .css({backgroundColor:'#b54335', color:'#1b3c5e'});
                    location.href = '/member/' + json.nickname + '?listing=' + json.stuff_id;
                }
            } else {
                $('html, body').animate({scrollTop: 0}, 'fast');
                $('#flash').text(json.flash + json.whom + '!')
                    .css('color', 'white')
                    .css('background', 'none');
                $('#messageform').hide();
            }
        },
        dataType: 'json',
        clearForm: true,
        resetForm: true
    };

    $('#send_message_form').ajaxForm(options);
    $('#market_message_form').ajaxForm(options);

    // Marketplace, contacting seller
    $('#listing_title').attr('disabled', 'disable');
    $('#usr_name').attr('disabled', 'disable');

};

// Reusable form features, note when using to properly correlate to html page
setup_form_features = function() {

  // Add new form ids here
  var form = undefined;
  switch(document.body.id) {
  case 'member_profile':
    form = $('#messageform');
    break;
  case 'product_info':
    form = $('#reviewform');
    break;
  case 'market_listing':
    form = $('#marketlistingform');
    break;
  }

  if (form) {

    // Initialize as hidden
    form.hide();

    // Better to do it this way, so each link click by logged-in user is not an Ajax call, thus straining the server
    $('.nonusr').click(function(e){
      e.preventDefault();
      $.getJSON(this.href, function(json) {
        if (json.is_usr == false) {
          $('html, body').animate({scrollTop: 0}, 'fast');
          $('#flash')
            .text(json.error)
            .css({backgroundColor:'#b54335', color:'#1b3c5e'});
        }
      });
    });

    // We already know user is logged-in, no need to check
    $('.formlnk').click(function(e) {
      e.preventDefault();
      form.toggle('slow'); // slideToggle jacks up css in IE7
    });
    $('.close').click(function(e) {
      e.preventDefault();
      form.hide('slow');
    });
  }
};

// A centralized function for all tallyable objects:  vote / rate / flag
setup_tally_features = function() {

    // Star rating
    $('input[@name=rating]').rating({
        callback: function(val) {
            var type = $('#rate_type').val();
            var id = $('#rate_id').val();
            ajax_call('rate', type, val, id);
        }
    });

    $('.voteup').click(function(e) {
        e.preventDefault();
        var id = $(this).parents('div:eq(1)').attr('id');
        id = id.split('-', 2)[1];
        ajax_call('voteup', this.name, 0, id);
    });

    $('.votedown').click(function(e) {
        e.preventDefault();
        var id = $(this).parents('div:eq(1)').attr('id');
        id = id.split('-', 2)[1];
        ajax_call('votedown', this.name, 0, id);
    });

    $('.flag').click(function(e) {
        e.preventDefault();
        var id = $(this).parents('div:eq(1)').attr('id');
        id = id.split('-', 2)[1];
        ajax_call('flag', this.name, 0, id);
    });

    var ajax_call = function(tally, type, val, id) {

        options = {
            type: 'GET',
            url: '/ajax/tallyable',
            data: {
                'tally': tally,
                'type': type,
                'rating': val,
                'id': id
            },
            dataType: 'json',
            success: function(resp) {
                callback(resp);
            }
        };

        $.ajax(options);

    };

    var callback = function(resp) {
        if(resp.is_usr == false) {
            $('html, body').animate({scrollTop: 0}, 'fast');
            $('#flash')
               .text(resp.error)
               .css({backgroundColor:'#b54335', color:'#1b3c5e'});
        }
        if (resp.tally == 'vote') {
            var div = $('div[@id='+resp.type+'-'+resp.id+']');
            div.find('.y').text(resp.y);
            div.find('.total').text(resp.y+resp.n);
        }
        if (resp.tally == 'rating') {
            $('#total_votes').text(resp.votes);
            $('#avg_rating').text(resp.avg);
        }
        if (resp.tally == 'flag') {
            var div = $('div[@id='+resp.type+'-'+resp.id+']');
            var img = div.find('a.flag').children().filter('img');
            img.attr('src', '/images/flag_red.png')
                .next().filter('.flag_cnt')
                .text(resp.count);
            if (resp.count == 3) {
                var div = $('div[@id='+resp.type+'-'+resp.id+']');
                div.children().filter('.flagged')
                    .text(resp.msg);
                div.find('.'+resp.type+'').remove();
            }
        }
    };

};


function simple_ajaxify(element) {
  element.ajaxForm();

  element.change(function() {element.submit();});
  element.children('input[type="submit"]').hide();
}


function openWindow(url, name, options) {
    window.open(url, name, options);
}

function getElementPosition(elementId) {
    var offsetTrail = document.getElementById(elementId);
    var offsetLeft = 0;
    var offsetTop = 0;
    while(offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 &&
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {left:offsetLeft, top:offsetTop};
}
