﻿Friend = {
  member_id: null,
  url: function(action) {
    return '/webservices/community/friend/' + action + '?friend_id='+Friend.member_id;
  },

  create_html: function (action) {
    var p = jQuery('div.vehicle_owner .friend_action'),
        addText = '<img style="margin-left:6px" alt="Add Friend" src="/images/icon_add_friend.gif"> ' +
          '<a href="' + Friend.url('add') + '">Add Friend<\/a>'; 
    p.removeClass('add_friend remove_friend').addClass(action+'_friend');
    if (action == 'add') p.html(addText);
    else {
      p.find('a').text('Added'); p.fadeOut(3000,function() {p.html('')});
    }
    p.find('a').click((action == 'add') ? Friend.add : Friend.remove);
  },

  add: function() {
    jQuery('div.vehicle_owner .friend_action').addClass('remove_friend').removeClass('add_friend');
    return vehiclePage.addRemoveFriends(Friend.url('add'),function() {Friend.create_html('is_friend')});
  },

  remove: function() {
    jQuery('div.vehicle_owner .friend_action').addClass('add_friend').removeClass('remove_friend');
    return vehiclePage.addRemoveFriends(Friend.url('remove'),function() {Friend.create_html('add')});
  }
}

Favorite = {
  setup_links : function(ride_id,favorite_id) {
    var is_favorite = Boolean(Number(favorite_id));
    Favorite.favorite_id = favorite_id;
    
    if (is_favorite) jQuery('#remove_favorite').show();
    else jQuery('#add_favorite').show();
    jQuery('#add_favorite,#remove_favorite').click(function() {
      if (this.rel == 'active') return false;
      this.rel = 'active';
      var link = jQuery(this),action = this.id.replace(/_.*$/,'');      
      var toggle = {add : '#remove_favorite', remove : '#add_favorite'};
      function showError(link,action) {
        link.hide();
        jQuery('#favorite_err').show().fadeOut(3000,function(){link.show()});
        link.get(0).rel = '';
      }
      var xhr = jQuery.ajax({
        data: {ride_id: ride_id, favorite_id: Favorite.favorite_id},
        dataType: 'json',
        success: function(data,textStatus) {
          if (data.response == 'Success') {
            var text = link.text();
            link.css('color','green').text('Successful ' + action);
            link.fadeOut(3000,function() {
              link.hide().css('color','').text(text);
              if (typeof data.favorite_id != 'undefined') {
                Favorite.favorite_id = data.favorite_id;
              }
              jQuery(toggle[action]).show();
              link.get(0).rel = '';
            });
          } else showError(link);
        },
        error: function() {showError(link)},
        type: 'post',
        url: '/webservices/community/favorite/' + action
      });
      return false;                            
    });
  }
};

Guestbook = {
  post_comment: function(guestbook_id) {
    jQuery.ajax({
      dataType:"json",
        url: '/webservices/community/guestbook/post_to_guestbook',
        data: jQuery('#guestbook_form_post [name]').serialize(),
        success: function(data, textStatus) {
          if (data.response == "Error") {
              jQuery(".error_red").text(data.error).show();
              jQuery("parent.a").addClass("error");
          } else {
              jQuery(".error_red").text("").hide();
              jQuery("form#guestbook_form_post textarea").removeClass("error");
              Guestbook.load_more(guestbook_id, 0);
              jQuery('#guestbook_form_post textarea').val('');
          }
        },
        error: function() {
          jQuery(".error_red").text("Unable to post to guestbook").show();
          jQuery("form#guestbook_form_post textarea").addClass("error");
        }
    });
 },
  remove_comment: function(guestbook_id, entry_id) {
    jQuery.ajax({
      dataType:"json",
        url: '/webservices/community/guestbook/remove_post',
        data: {guestbook_id : guestbook_id, entry_id : entry_id},
        success: function(data, textStatus) {
              Guestbook.load_more(guestbook_id, 0);      
        },
        error: function() {
        }
    });
 },
 load : function(guestbook_id) {
   jQuery('p.error').hide();
   jQuery('#guestbook_loading').show();
   jQuery.ajax({
     dataType:"json",
       url: '/webservices/community/guestbook/get_rendered_guestbook',
       data: {guestbook_id : guestbook_id},
       success: function(data) {
         jQuery('#guestbook_loading').hide();
         if (data.response == 'Success') {
           start_at = (data.count==0)?'':'1-';
           jQuery('#guestbook_post_count').html('Displaying entries '+
             start_at + data.count + ' of ' + data.total);
           jQuery('#header_bottom .guestbook_link').text(data.total + ' guestbook comment' + (data.total == 1? '' : 's'));
           jQuery('#guestbook_comments').html(data.html);
           sparkleText('a.insider,a.staff');
           if(data.count == data.total){
               jQuery('.loadMorePosts').hide();
           }
         } else {
           jQuery('p.error').show();
         }
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) {
         jQuery('#guestbook_loading').hide();
         jQuery('p.error').show();
       }
    });
  },
  load_more : function(guestbook_id, more) {
   jQuery('p.error').hide();
   jQuery('#guestbook_loading').show();
   var end = jQuery('#guestbook_comments .comment_box').length + more;
   if (end < 5) { end = 5;} //Load at least 5 total   
   jQuery.ajax({
     dataType:"json",
       url: '/webservices/community/guestbook/get_rendered_guestbook',
       data: {guestbook_id : guestbook_id, end_at : end},
       success: function(data) {
         jQuery('#guestbook_loading').hide();
         if (data.response == 'Success') {
           start_at = (data.count==0)?'':'1-';
           jQuery('#guestbook_post_count').html('Displaying entries '+
             start_at + data.count + ' of ' + data.total);
           jQuery('#header_bottom .guestbook_link').text(data.total + ' guestbook comment' + (data.total == 1? '' : 's'));
           jQuery('#guestbook_comments').html(data.html);
           sparkleText('a.insider,a.staff');
           if(data.count == data.total){
               jQuery('.loadMorePosts').hide();
           } else {
               jQuery('.loadMorePosts').show();
           }

         } else {
           jQuery('p.error').show();
         }
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) {
         jQuery('#guestbook_loading').hide();
         jQuery('p.error').show();
       }
    });
  }
}

vehiclePage = {
  popup: function(href,name,height,width) {
    if (!height) height=500;
    if (!width) width=350;
    return window.open(href,name,'width='+width+',resizeable,height='+height);
  },
  addRemoveFriends: function(href,callback) {
    jQuery.get(href,null,function(txt) {
      var obj = JSON.parse(txt);
      if (obj.response == 'Success' && callback) callback(obj);      
    });
    return false;
  },
  loadRelatedRidesCallback: function(json) {
    if(json.response == 'Success') {
      jQuery(".related_rides div.scrolling_div").html(json.html);
      jQuery(".related_rides").css("display", "block");
    }
  },
  loadRelatedRides: function(pageId) {
    var rides_div = jQuery(".related_rides div.scrolling_div");
    jQuery.getJSON('http://www.cardomain.com/webservices/community/ride/get_related_rides', {ride_id: pageId}, vehiclePage.loadRelatedRidesCallback);
  }
};

var BallotBox = function(pageId, voteSectionId,alertElm) {
  var voteSect = jQuery('#'+voteSectionId),
      href = 'http://www.cardomain.com/webservices/community/rating/history?page_id=' + pageId,
      votes = {},
      self = this,
      animator = {},
      animatorMethod;
  
  function message(text,err) {
    self.alertElm.css('color','').text(text);
    if (err) self.alertElm.css('color','red');
    else setTimeout(function() {self.clearAlert()},4000);
  }
  this.alertElm = alertElm;
  this.clearAlert = function() {
    this.alertElm.text('');
  }
  this.hide = function() {
    var animator = {};
    animator[animatorMethod] = 'hide';
    voteSect.animate(animator,1500);
  }
  this.show = function(method) {
    voteSect.hide();
    message("Loading your current votes...");
    animatorMethod = method;
    function loader(data) {
      var obj = JSON.parse(data);
      function success() {
        var cat,animator = {};
        for (cat in obj.vote_history) {
          document.getElementById('selected-rating-'+cat).style.width = (obj.vote_history[cat] * 15) + 'px';
        }
        animator[animatorMethod] = 'show'
        voteSect.animate(animator,1500,function(){self.clearAlert()});
      }
      function failure() {
        switch(obj.error) {
          case 'unknown_page_id'  : message('Unknown Page ID',true);        break;
          case 'no_page_id'       : message('No Page ID',true);             break;
          case 'not_logged_in'    : message('You are not logged in',true);  break;
          default                 : message('general error',true);          break;
        }                                              
      }
      if (obj && (obj.response=="Success") && (data.charAt(0) == '{')) success();
      else failure();
    }
    jQuery.get(href,null,loader);
    return false;
  }

  this.setVote = function(cat, vote) {
    document.getElementById("selected-rating-" + cat).style.width = (15 * vote) + 'px';
    votes[cat] = vote;
    return false;
  }

  this.saveVotes = function() {
    var href = "/webservices/community/rating/vote?page_id=" + pageId,
        cat,votecnt=0;
        
    for (cat in votes) {
      href += "&votes=cat_" + cat + ":" + votes[cat];
      votecnt++;
    }
    if (votecnt == 0) message("You did not cast any votes.");
    else {
      message("Your votes are being submitted..."); 
      jQuery.get(href,null,function(data) {
        var obj = JSON.parse(data);
        if (obj.response) {
          message("Thank you for voting.");
          votes = {};
        } else message("An error occurred casting your vote.  Please try again.",true);
      });
    }
    self.hide();
    return false;
  }
}
/*
Copyright (c) 2005 JSON.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The Software shall be used for Good, not Evil.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

Array.prototype.______array = '______array';

var JSON = {
    org: 'http://www.JSON.org',
    copyright: '(c)2005 JSON.org',
    license: 'http://www.crockford.com/JSON/license.html',

    stringify: function (arg) {
        var c, i, l, s = '', v;

        switch (typeof arg) {
        case 'object':
            if (arg) {
                if (arg.______array == '______array') {
                    for (i = 0; i < arg.length; ++i) {
                        v = this.stringify(arg[i]);
                        if (s) {
                            s += ',';
                        }
                        s += v;
                    }
                    return '[' + s + ']';
                } else if (typeof arg.toString != 'undefined') {
                    for (i in arg) {
                        v = arg[i];
                        if (typeof v != 'undefined' && typeof v != 'function') {
                            v = this.stringify(v);
                            if (s) {
                                s += ',';
                            }
                            s += this.stringify(i) + ':' + v;
                        }
                    }
                    return '{' + s + '}';
                }
            }
            return 'null';
        case 'number':
            return isFinite(arg) ? String(arg) : 'null';
        case 'string':
            l = arg.length;
            s = '"';
            for (i = 0; i < l; i += 1) {
                c = arg.charAt(i);
                if (c >= ' ') {
                    if (c == '\\' || c == '"') {
                        s += '\\';
                    }
                    s += c;
                } else {
                    switch (c) {
                        case '\b':
                            s += '\\b';
                            break;
                        case '\f':
                            s += '\\f';
                            break;
                        case '\n':
                            s += '\\n';
                            break;
                        case '\r':
                            s += '\\r';
                            break;
                        case '\t':
                            s += '\\t';
                            break;
                        default:
                            c = c.charCodeAt();
                            s += '\\u00' + Math.floor(c / 16).toString(16) +
                                (c % 16).toString(16);
                    }
                }
            }
            return s + '"';
        case 'boolean':
            return String(arg);
        default:
            return 'null';
        }
    },
    parse: function (text) {
        var at = 0;
        var ch = ' ';

        function error(m) {
            throw {
                name: 'JSONError',
                message: m,
                at: at - 1,
                text: text
            };
        }

        function next() {
            ch = text.charAt(at);
            at += 1;
            return ch;
        }

        function white() {
            while (ch != '' && ch <= ' ') {
                next();
            }
        }

        function str() {
            var i, s = '', t, u;

            if (ch == '"') {
outer:          while (next()) {
                    if (ch == '"') {
                        next();
                        return s;
                    } else if (ch == '\\') {
                        switch (next()) {
                        case 'b':
                            s += '\b';
                            break;
                        case 'f':
                            s += '\f';
                            break;
                        case 'n':
                            s += '\n';
                            break;
                        case 'r':
                            s += '\r';
                            break;
                        case 't':
                            s += '\t';
                            break;
                        case 'u':
                            u = 0;
                            for (i = 0; i < 4; i += 1) {
                                t = parseInt(next(), 16);
                                if (!isFinite(t)) {
                                    break outer;
                                }
                                u = u * 16 + t;
                            }
                            s += String.fromCharCode(u);
                            break;
                        default:
                            s += ch;
                        }
                    } else {
                        s += ch;
                    }
                }
            }
            error("Bad string");
        }

        function arr() {
            var a = [];

            if (ch == '[') {
                next();
                white();
                if (ch == ']') {
                    next();
                    return a;
                }
                while (ch) {
                    a.push(val());
                    white();
                    if (ch == ']') {
                        next();
                        return a;
                    } else if (ch != ',') {
                        break;
                    }
                    next();
                    white();
                }
            }
            error("Bad array");
        }

        function obj() {
            var k, o = {};

            if (ch == '{') {
                next();
                white();
                if (ch == '}') {
                    next();
                    return o;
                }
                while (ch) {
                    k = str();
                    white();
                    if (ch != ':') {
                        break;
                    }
                    next();
                    o[k] = val();
                    white();
                    if (ch == '}') {
                        next();
                        return o;
                    } else if (ch != ',') {
                        break;
                    }
                    next();
                    white();
                }
            }
            error("Bad object");
        }

        function num() {
            var n = '', v;
            if (ch == '-') {
                n = '-';
                next();
            }
            while (ch >= '0' && ch <= '9') {
                n += ch;
                next();
            }
            if (ch == '.') {
                n += '.';
                while (next() && ch >= '0' && ch <= '9') {
                    n += ch;
                }
            }
            if (ch == 'e' || ch == 'E') {
                n += 'e';
                next();
                if (ch == '-' || ch == '+') {
                    n += ch;
                    next();
                }
                while (ch >= '0' && ch <= '9') {
                    n += ch;
                    next();
                }
            }
            v = +n;
            if (!isFinite(v)) {
                error("Bad number");
            } else {
                return v;
            }
        }

        function word() {
            switch (ch) {
                case 't':
                    if (next() == 'r' && next() == 'u' && next() == 'e') {
                        next();
                        return true;
                    }
                    break;
                case 'f':
                    if (next() == 'a' && next() == 'l' && next() == 's' &&
                            next() == 'e') {
                        next();
                        return false;
                    }
                    break;
                case 'n':
                    if (next() == 'u' && next() == 'l' && next() == 'l') {
                        next();
                        return null;
                    }
                    break;
            }
            error("Syntax error");
        }

        function val() {
            white();
            switch (ch) {
                case '{':
                    return obj();
                case '[':
                    return arr();
                case '"':
                    return str();
                case '-':
                    return num();
                default:
                    return ch >= '0' && ch <= '9' ? num() : word();
            }
        }

        return val();
    }
};
/*
 * Tooltip - jQuery plugin  for styled tooltips
 *
 * Copyright (c) 2006 Jï¿½rn Zaefferer, Stefan Petre
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * HJ: Parameterized tooltip id, body class and url class values
 *
 */

/**
 * Display a customized tooltip instead of the default one
 * for every selected element. The tooltip behaviour mimics
 * the default one, but lets you style the tooltip and
 * specify the delay before displaying it.
 *
 * In addition, it displays the href value, if it is available.
 * 
 * To style the tooltip, use these selectors in your stylesheet:
 *
 * #tooltip - The tooltip container
 *
 * #tooltip h3 - The tooltip title
 *
 * #tooltip p.body - The tooltip body, shown when using showBody
 *
 * #tooltip p.url - The tooltip url, shown when using showURL
 *
 * @example $('a, input, img').Tooltip();
 * @desc Shows tooltips for anchors, inputs and images, if they have a title
 *
 * @example $('label').Tooltip({
 *   delay: 0,
 *   track: true,
 *   event: "click"
 * });
 * @desc Shows tooltips for labels with no delay, tracking mousemovement, displaying the tooltip when the label is clicked.
 *
 * @example // modify global settings
 * $.extend($.fn.Tooltip.defaults, {
 * 	track: true,
 * 	delay: 0,
 * 	showURL: false,
 * 	showBody: " - ",
 *  fixPNG: true
 * });
 * // setup fancy tooltips
 * $('a.pretty').Tooltip({
 * 	 extraClass: "fancy"
 * });
 $('img.pretty').Tooltip({
 * 	 extraClass: "fancy-img",
 * });
 * @desc This example starts with modifying the global settings, applying them to all following Tooltips; Afterwards, Tooltips for anchors with class pretty are created with an extra class for the Tooltip: "fancy" for anchors, "fancy-img" for images
 *
 * @param Object settings (optional) Customize your Tooltips
 * @option Number delay The number of milliseconds before a tooltip is display, default is 250
 * @option String event The event on which the tooltip is displayed, default is "mouseover", "click" works fine, too
 * @option Boolean track If true, let the tooltip track the mousemovement, default is false
 * @option Boolean showURL If true, shows the href or src attribute within p.url, default is true
 * @option String showBody If specified, uses the String to split the title, displaying the first part in the h3 tag, all following in the p.body tag, separated with <br/>s, default is null
 * @option String extraClass If specified, adds the class to the tooltip helper, default is null
 * @option Boolean fixPNG If true, fixes transparent PNGs in IE, default is false
 *
 * @name Tooltip
 * @type jQuery
 * @cat Plugins/Tooltip
 * @author Jï¿½rn Zaefferer (http://bassistance.de)
 */
(function($) {
	
	// the tooltip element
	var helper,
		// it's title part
		tTitle,
		// it's body part
		tBody,
		// it's url part
		tUrl,
		// the current tooltipped element
		current,
		// the title of the current element, used for restoring
		oldTitle,
		// timeout id for delayed tooltips
		tID;
	
	// the public plugin method
	$.fn.Tooltip = function(settings) {
		// setup configuration
		// TODO: allow multiple arguments to extend, see bug #344
		settings = $.extend($.extend({}, arguments.callee.defaults), settings || {});
	
		// there can be only one tooltip helper
		if( !helper ) {
			// create the helper, h3 for title, div for url
			helper = $('<div id="'+settings.tipId+'"><h3></h3><p class="'+settings.bodyClass+'"></p><p class="'+settings.urlClass+'"></p></div>')
				// hide it at first
				.hide()
				// move to top and position absolute, to let it follow the mouse
				.css({ position: 'absolute', zIndex: 3000 })
				// add to document
				.appendTo('body');
				
			// save references to title and url elements
			tTitle = $('h3', helper);
			tBody = $('p:eq(0)', helper);
			tUrl = $('p:eq(1)', helper);
		}
		
		// bind events for every selected element with a title attribute
		$(this).filter('[title]')
			// save settings into each element
			// TODO: pass settings via event system, not yet possible
			.each(function() {
				this.tSettings = settings;
			})
			// bind events
			.bind("mouseover", save)
			.bind(settings.event, handle);
		return this;
	};
	
	// main event handler to start showing tooltips
	function handle(event) {
		// show helper, either with timeout or on instant
		if( this.tSettings.delay )
			tID = setTimeout(show, this.tSettings.delay);
		else
			show();
		
		// if selected, update the helper position when the mouse moves
		if(this.tSettings.track)
			$('body').bind('mousemove', update);
			
		// update at least once
		update(event);
		
		// hide the helper when the mouse moves out of the element
		$(this).bind('mouseout', hide);
	}
	
	// save elements title before the tooltip is displayed
	function save() {
		// if this is the current source, or it has no title (occurs with click event), stop
		if(this == current || !this.title)
			return;
		// save current
		current = this;
		
		var source = $(this),title,            // HJ : added local title var
			settings = this.tSettings;
			
		// save title, remove from element and set to helper
		oldTitle = title = source.attr('title');
		source.attr('title','');
		if(settings.showBody) {
			var parts = title.split(settings.showBody),part,i;
			tTitle.html(parts.shift());
			tBody.empty();
      tBody.append(parts.join('<br />'));
			if(tBody.html())
				tBody.show();
			else
				tBody.hide();
		} else {
			tTitle.html(title);
			tBody.hide();
		}
		
		// if element has href or src, add and show it, otherwise hide it
		href = (source.attr('href') || source.attr('src'));
		if( settings.showURL && href )
			tUrl.html(href.replace('http://', '')).show();
		else 
			tUrl.hide();
		
		// add an optional class for this tip
		if( settings.extraClass ) {
			helper.addClass(settings.extraClass);
		}
		// fix PNG background for IE
		if (settings.fixPNG && $.browser.msie ) {
			helper.each(function () {
				if (this.currentStyle.backgroundImage != 'none') {
					var image = this.currentStyle.backgroundImage;
					image = image.substring(5, image.length - 2);
					$(this).css({
						'backgroundImage': 'none',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
					});
				}
			});
		}
	}
	
	// delete timeout and show helper
	function show() {
		tID = null;
		helper.show();
		update();
	}
	
	/**
	 * callback for mousemove
	 * updates the helper position
	 * removes itself when no current element
	 */
	function update(event)	{
		// if no current element is available, remove this listener
		if( current == null ) {
			$('body').unbind('mousemove', update);
			return;	
		}
		
		var left = helper[0].offsetLeft;
		var top = helper[0].offsetTop;
		if(event) {
			// get the current mouse position
			function pos(c) {
				var p = c == 'X' ? 'Left' : 'Top';
				return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
			}
			// position the helper 15 pixel to bottom right, starting from mouse position
			left = pos('X') + 15;
			top = pos('Y') + 15;
			helper.css({
				left: left + 'px',
				top: top + 'px'
			});
		}
		
		var v = viewport(),
			h = helper[0];
		// check horizontal position
		if(v.x + v.cx < h.offsetLeft + h.offsetWidth) {
			left -= h.offsetWidth + 20;
			helper.css({left: left + 'px'});
		}
		// check vertical position
		if(v.y + v.cy < h.offsetTop + h.offsetHeight) {
			top -= h.offsetHeight + 20;
			helper.css({top: top + 'px'});
		}
	}
	
	function viewport() {
		var e = document.documentElement || {},
			b = document.body || {},
			w = window;

		return {
			x: w.pageXOffset || e.scrollLeft || b.scrollLeft || 0,
			y: w.pageYOffset || e.scrollTop || b.scrollTop || 0,
			cx: Math.min( e.clientWidth, b.clientWidth, w.innerWidth ),
			cy: Math.min( e.clientHeight, b.clientHeight, w.innerHeight )
		};
	}
	
	// hide helper and restore added classes and the title
	function hide() {
		// clear timeout if possible
		if(tID)
			clearTimeout(tID);
		// no more current element
		current = null;
		helper.hide();
		// remove optional class
		if( this.tSettings.extraClass ) {
			helper.removeClass( this.tSettings.extraClass);
		}
		
		// restore title and remove this listener
		$(this)
			.attr('title', oldTitle)
			.unbind('mouseout', hide);
			
		// remove PNG background fix for IE
		if( this.tSettings.fixPNG && $.browser.msie ) {
			helper.each(function () {
				$(this).css({'filter': '', backgroundImage: ''});
			});
		}
	}
	
	// define global defaults, editable by client
	$.fn.Tooltip.defaults = {
                tipId: 'tooltip',
                bodyClass: 'body',
                urlClass: 'url',
                delay: 250,
                event: 'mouseover',
                track: false,
                showURL: true,
                showBody: null,
                extraClass: null,
                fixPNG: false
	};

})(jQuery);
function sparkleText(selector) {
  function prepareElm(elm) {
    var jElm = jQuery(elm),sp;
    var txta = jElm.text().split('');
    jElm.empty();
    for (var i=0; i<txta.length; i++) 
      if (sp = document.createElement('span')) {
        sp.appendChild(document.createTextNode(txta[i])); 
        elm.appendChild(sp);
      }
  }
  function randomColor() {
    function n() {return Math.ceil((Math.random()*1000) % 256);}
    return 'rgb('+n()+','+n()+','+n()+')';
  }
  function animate(elm,i) {
    var spans = jQuery('span',elm).css('color','');
    function animElm(sp) {sp.css('color',randomColor())}
    if (typeof i == 'number') animElm(spans.slice(i,i+1));
    else {
      for (var i=0; i<spans.length; i++)
        setTimeout((function(n) {return function() {animate(elm,n)}})(i),i*110);
      setTimeout(function(){spans.css('color','')},i*110);
    }               
  }

  jQuery(selector).each(function() {
    var elm = this;                                        
    prepareElm(elm);
    animate(elm);
    setInterval(function() {animate(elm)},12000);
  });
}

/* VAST related functions */
/*
 *  CD_getVast takes two arguments:
 *    sel : a jQuery selector to locate the target element for the VAST script
 *          usually, this should be the element where the CD_getVast call occurs
 *    arg : an object with a few properties for VAST forsale car selection:
 *      tlocation : a free-form string, e.g., 'city, state country'
 *      make      : car make                                       
 *      model     : car model
 *      year      : car year
 *      q         : a free-form query string, e.g. '2001 honda accord seattle wa'
 *    
 */

function CD_getVast(sel,arg) {
  var scriptURL,elem,script;
  
  function CD_VastWidget(arg) {
    function getWidget(arg) {
        var legal_props = {channel_id:1,ipaddress:1,seo_string:1,tlocation:1,make:1,model:1,year:1,q:1} 
      var widgetArg = {
        apikey     : '12706312896146373215521101211671',
        widget_id  : 'vast_cardomain',
        channel_id : '1',
        local      : 'true',
        redirect   : CD_VastWidget.redirect,
        ipaddress  : '',
        tlocation  : '',
        make       : '',
        model      : '',                                                       
        year       : '',
        seo_string : '',
        q          : ''
      }               
      for (var property in legal_props) {
        if (typeof arg[property] == 'string')
          widgetArg[property] = arg[property];
      }
      return new VastWidget(widgetArg);
    }
    setTimeout(function() {
      var widget = getWidget(arg);
      widget.userCallback = function() {
        this.params.redirect = this.params.redirect+'?make_id='+this.getParam('make')+'&model_id='+this.getParam('model')+'&tlocation='+this.getParam('tlocation')+'&keywords='+this.getParam('q')+'&year='+this.getParam('year')+'&hasimage=y';
      }
    },1);
  }
  
  CD_VastWidget.redirect = 'http://usedcars.cardomain.com/cars/';

  if (elem = jQuery(sel).get(0)) {
    if (script = document.createElement('script')) {
      script.type = 'text/javascript';
      script.id = 'vast_cardomain';
      script.src = 'http://widgets.vast.com/vastsearch.js';
      elem.appendChild(script);
      jQuery(window).load(function() {                                
        setTimeout(function() {CD_VastWidget(arg);},1);
      });
    }
  }
}  
      
      
function ShowImage(url, width, height, img) {
  // Max ridepage dimension is 575
  var imgHeight, imgWidth;
  if (img && img.tagName == 'IMG') {
    imgHeight = img.height;
    imgWidth = img.width;
    if (imgHeight > imgWidth) {
      height = 615;
      width = Math.round((imgWidth/imgHeight) * 600);
    } else {
      width = 600;
      height = Math.round((imgHeight/imgWidth) * 600) + 15;
    }
  }
  window.open(url,"image_win","height=" + height + ",width=" + width + ",statusbar=no,location=no,menubar=no,toolbar=no,resizable=no ");
}

function checktitle() {
  if (document.guestbook_form.title.value.length < 8) {
    alert ('Your vehicle summary must be at least 8 characters.'); 
    return false;
  }
  return true;
}

function checksummary() {
  if (document.summary_form.summary_text.value.length < 8) {
    alert ('Your vehicle summary must be at least 8 characters.'); 
    return false;
  }
  return true;
}

function checkpagetext() {
  if (document.edit_form.text.value.length < 30) {
    alert ('Your page text must be at least 30 characters.'); 
    return false;
  } 
  return true;
}

function show_remaining_chars(element,maxlen) {
  var remaining_text = "Character limit reached";
  if (element.value.length < maxlen ) { remaining_text = maxlen-element.value.length +' characters remaining'; }
  document.getElementById('remaining_chars').firstChild.data = remaining_text;
}

// Adds an input box for user-supplied ride modifications
function add_mod_input(ele) {
  var ele = jQuery(ele);

  var cl = jQuery('<div class="element-wrap"></div>');
  cl.css('display', 'none');
  var mod_id = jQuery("input[type='hidden']", ele.parent().parent()).attr('value');
  var inp = jQuery('<label>Custom Mod</label><input type="text" name="' + mod_id + '_usermod_'
    + (MOD_INPUT_INC++) + '" maxlength="50" class="user_mod"> <a href="#" class="remove_user_mod">Remove</a>');
  cl.append(jQuery('<div class="user_custom_mod_input"></div>').append(inp));
  cl.insertBefore(ele.parent().parent());
  cl.slideDown('fast');

  jQuery('.user_custom_mod_input .remove_user_mod').click(function() {
    var ele = jQuery(this).parent().parent();
    ele.slideUp('fast', function() { ele.remove() } );
    return false;
  });

  return;
}

