//**************
var loaded = false;
var lightbox;

function dbSaveOrds()
{
  if(!loaded){loaded=true; return;}
   var tbl = document.getElementById("table-my-plan");
   if(!tbl)return;
   
   var rows = new Array(0);
   var j=0;
   for(var i=0; i < tbl.rows.length; i++)   
    
	
	//alert('s');
	
	if(tbl.rows[i].getAttribute("spid")!=null) 
    {	
      rows[j]=tbl.rows[i].getAttribute("spid");
	  j++;
	}
	  
	 
   $.post(window.location+"?wnd=true&act=arrange_plans",{ids:rows.toString()},function(r){if(r.search('OK')==-1)alert(r);});
   
}

function pop(item){
			lightbox.show({
				'width': 960,
				'url': item.getAttribute("rel"),
				'callback': function(lightbox) {
					
					$('<a class="print-button" href="#">Print</a>').appendTo(this.wrappers.lightbox).click(function(){
						
						var nw = window.open('/layout/templates/javascript/print-contact.html', 'print-plot', 'height=600px,width=980px, scrollbars, resizable');

						return false;
					});
				}
			});					
		}

(function($){

	$(function(){
		
		
		if(jQuery.browser.msie && parseInt(jQuery.browser.version) < 7 ) {
			var path =  $('head link[href$="main.css"]').attr('href');
			
			var link = document.createElement("link");
			link.setAttribute("rel", "stylesheet");
			link.setAttribute("type", "text/css");
			link.setAttribute("href", path.substr( 0, path.indexOf('main.css') )+ 'ie6.css');
			link.onreadystatechange = function() {
				if(this.readyState == 'complete') {
					var path =  $('head script[src$="main.js"]').attr('src');
					var script = document.createElement('script');
					script.type = 'text/javascript';
					script.src = path.substr( 0, path.indexOf('main.js') )+ 'ie6.js';
					document.getElementsByTagName("head")[0].appendChild(script)
				}
			}
			document.getElementsByTagName("head")[0].appendChild(link)
			
			
			
			
		}
		
		
		
		$('.tab-controller').not('.disabled').each(function(){
			
			//Tabs
			var first = true;
			var tabs = {};
			var currentTab = false;
			var working = false;
			var speed = 'slow';
			
			var changeTab = function(id){
				if(!working) {
					working = true;
					if( typeof tabs[id] == 'object' && id != currentTab) {
						
						if(currentTab) {
							tabs[currentTab].handel.removeClass('current');
							tabs[currentTab].view.animate({'opacity': 0, 'top': '50px'}, speed, function(){
								$(this).css('display', 'none');
								working = false;
							});
							
						}
						currentTab = id;
						tabs[currentTab].handel.addClass('current');
						tabs[currentTab].view.css({'opacity': 0, 'display': 'block', 'top': '0px'}).animate({'opacity': 1}, speed);
					} else {
						working = false;
					}
				}
			}
			
			
			
			$('.tab-view .tab', this.parentNode).css({
				'position': 'absolute',
				'display': 'none',
				'top': 0
			});
			
			
			$('a', this).click(function(){
				changeTab( this.href.substr(this.href.indexOf('#')) );
				return false;
				
			}).each(function(){
				var i;
				if( (i = this.href.indexOf('#')) >= 0 ) {
					tabs[ this.href.substr(i) ] = {
						'handel': $(this.parentNode),
						'view': $('.tab-view .tab-' + this.href.substr(i + 1) )
					};
					
					
					$('a', this).not(this).click(function(){
						changeTab( this.href.substr(this.href.indexOf('#')) );
						return false;
					});
					
					if(first) {
						currentTab = this.href.substr(i);
						tabs[ currentTab ].handel.addClass('current');
						tabs[ currentTab ].view.css('display', 'block');
						first = false;
					}
				}
			});
			
			if(window.location.hash)
				changeTab(window.location.hash);
			
		});
		//End Tab
		
		
		
		
		$('form.register-form').submit(function(){	
			
			$.cookie('registerFirstName', $('input[name="first-name"]').val());
			$.cookie('registerLastName', $('input[name="second-name"]').val());
			$.cookie('registerEmail', $('input[name="email"]').val());
			
			return true;
		})
		
		
		$('.#user-controlls a.login').click(function(){
			$('.#user-controlls form.#login_like_form').css({'opacity': 0, 'display': 'block', 'top': '-50px'}).animate({'opacity': 1, 'top': '10px'}, 'slow');
			return false;
		});
		$('.#user-controlls form.login-form span').click(function(){
			$('.#user-controlls form').animate({'opacity': 0, 'top': '60px'}, 'slow', function(){
				$(this).css('display', 'none');
			});
		});
		
		$('.#user-controlls form.login-form #button_change_password').click(function(){
			$('.#user-controlls form').animate({'opacity': 0, 'top': '60px'}, 'slow', function(){
				$(this).css('display', 'none');
				$('.#user-controlls form.#change_password_form').css({'opacity': 0, 'display': 'block', 'top': '-50px'}).animate({'opacity': 1, 'top': '10px'}, 'slow');
			});
		});
		
		$('form.register:first').each(function(){
			$('input[name="first-name"]').val( $.cookie('registerFirstName') );
			$('input[name="last-name"]').val( $.cookie('registerLastName') );
			$('input[name="email"]').val( $.cookie('registerEmail') );
		});
		
		
		lightbox = {
			'isLoaded': false,
			'options': {},
			'wrappers': {
			},
			
			'init': function(){
				if( !this.isLoaded ) {
					this.isLoaded = true;
					this.wrappers.cover = $('<div id="lightbox-cover">').appendTo('body').click(function(){ lightbox.hide() });
					$('<div id="lightbox-wrapper"><div class="c1"></div><div class="c2"></div><div class="c3"></div><div class="c4"></div><div class="c5"></div><div class="c6"></div><div class="c7"></div><div class="c8"></div><a class="close" href=""></a><div id="lightbox"></div></div>').appendTo('body');
					this.wrappers.wrapper = $('#lightbox-wrapper');
					this.wrappers.lightbox = $('#lightbox');
					$('#lightbox-wrapper a.close').click(function(){
						lightbox.hide();
						return false;
					});
				}
			},
			
			'resize': function(w) {
				
				if(!w) {
					w = this.options.width;
				}
				
				this.wrappers.wrapper.css({
					'top': $(document).scrollTop() + 50 + 'px',
					'left': parseInt( ($(window).width() / 2) - ( w / 2 ) + document.body.scrollLeft ) + 'px',
					'width': w
				});
				
				setTimeout(function(){
					$('#lightbox-wrapper .c4, #lightbox-wrapper .c5').css({
						'height': lightbox.wrappers.lightbox.outerHeight()
					});
				}, 10);
				
				
				$('#lightbox-wrapper .c2, #lightbox-wrapper .c7').css({
					'width': w
				});			
				
				this.wrappers.cover.css({'height': $(document).height()});
				this.options.width = w;
			},
			
			'hide': function(){
				this.wrappers.cover.animate({'opacity': 0}, 'fast', null, function(){
					$(this).css('display', 'none');
				});
				
				this.wrappers.wrapper.animate({'opacity': 0}, 'fast', null, function(){
					$(this).css('display', 'none');
				});
				
				if( $.browser.msie && parseInt($.browser.version) <= 6 ) {
					//Fix IE6 Private form
					$('#src_form select.input-text').show();
				}
			},
			
			'show': function(options) {
				this.options = options;
				this.init();
				
				
				this.wrappers.cover.css({
					'display': 'block', 
					'opacity': 0,
					'height': $(document).height()
				}).animate({'opacity': 0.75}, 'fast');			
				
				if(options.url) {
					
					this.wrappers.lightbox.html('<div class="loading"></div>');
					this.resize(options.width)
					
					this.wrappers.wrapper.css({
						'display': 'block', 
						'opacity': 0
					}).animate({'opacity': 1}, 'fast');;
					
					
					$.ajax({
						'success': function(html, textStatus){
							lightbox.wrappers.lightbox.html(html);
							lightbox.resize(options.width)
							if(options.callback)
								options.callback.call(lightbox);
						},
						'data': options.data,
						'dataType': 'text',
						'url': options.url
					});
					
				}
				
				if( $.browser.msie && parseInt($.browser.version) <= 6 ) {
					//Fix IE6 Private form
					$('#src_form select.input-text').hide();
				}
				
			}
			
		};
		
		
		$('#user-controlls a.contact-us').click(function(){
			
			lightbox.show({
				'width': 1000,
				'url': this.href
			});	
			
			return false;
		});
		
		
		$('.lightbox-ajax').click(function(){
		  var options = {
				'width': 960,
				'url': this.href,
				'data': {}
			};
		/*	
		  var specs = this.getAttribute("rel");
		       if(specs)
			   {
			     attrs = specs.split("|");
				 
                 for(var i = 0; i< attrs.length; i++)
				  {
             		var val = attrs[i].split("=");
					options[val[0]] = val[1];
				  }
			   }*/
				lightbox.show(options);
			return false;
		});
		
		$('.lightbox-ajax2').click(function(){
		  var options = {
			    'width': 1000,
				'url': this.href,
				'data': {}
			};
		/*	
		  var specs = this.getAttribute("rel");
		       if(specs)
			   {
			     attrs = specs.split("|");
				 
                 for(var i = 0; i< attrs.length; i++)
				  {
             		var val = attrs[i].split("=");
					options[val[0]] = val[1];
				  }
			   }*/
				lightbox.show(options);
			return false;
		});		
		
		
		
		
		var addToPlan = function(row) {
			
			$plus = $('a.plus', row);
			$('input[type="checkbox"]', row).get(0).checked = 'checked';
			$plus.hide();
			
			$('span.done a', row).click(function() {
				var row = $(this).parents('tr:first');
				$('span.done', row).css('display', 'none');
				$('input[type="checkbox"]', row).get(0).checked = false;
				$('a.plus', row).show();
				row.removeClass('selected');
				return false;
			});
			
			$('span.done', row).css('display', 'block');
			row.addClass('selected');
		}
		
		
		$('.search-resaults tbody a').not('.plus, .minus').click(function() {
			var row = $(this).parents('tr:first');
			var id = row.attr('id').substr( 'product-id-'.length );
			lightbox.show({
				'width': 960,
				'url': this.href,				
				'callback': function(){
					
					$('.title .button', lightbox.wrappers.lightbox).click(function() {
						addToPlan(row);
						$(this).css('visibility', 'hidden');
						return false;
					});
					
					if( $('.plus', row).css('display') == 'none' ) {
						$('.title .button', lightbox.wrappers.lightbox).css('visibility', 'hidden');
					}
					
					
					
				
					
				}
			});
			
			
			return false;
		});
		
		
		
		$('.search-resaults-plan tbody tr .last-column div').each(function() {
			var a = document.createElement('a');
			a.innerHTML = 'remove';
			a.className = 'remove';
			$(a).click(function() {
				
				$.ajax({
					'data': {
						'act': 'remove',
						'param': $(this).parents('tr:first').attr('rowid'),
						'order_field':	'company_name',
						'order_type':	'ASC'
					},
					'type': 'post',
					'url': '/private/search?wnd=true&sid=fsvpc62ts1kkhc2m6upklnqur2'
				});
				
				var table = $(this).parents('tbody:first');
				$(this).parents('tr:first').remove();
				
				$('tr', table).removeClass('odd');
				$('tr:even', table).addClass('odd');
				
				return false;
			});
			this.appendChild(a);
		});
		
	
		
	
		
		
		(function(){
			
			var dragging = false;
			
			var resetArrows = function(table) {
				var trs = $('tbody tr', table).removeClass('odd');
				$('tbody tr:even', table).addClass('odd')
				$('.up, .down', table).css('display', 'block');
				if(trs.length) {
					var first = trs.get(0);
					var last = trs.get(trs.length - 1)
					$('.up', first).css('display', 'none');
					$('.down', last).css('display', 'none');
					
				}
				dbSaveOrds();
			}
		
		
		
			$('table.sortable').each(function(){
				var dragging = false;
				var offsetTop = 0;
				var offsetMouse = 0;
				var $table = $(this);
				var trs = $('tbody tr', this);
				var wrapper = $('<div class="sortable-table-wrapper">').css('position', 'relative').insertAfter(this).append(this);
				var offsettHead = $('tbody tr:first', this).position().top - 50;
				var tableHeight = $table.height();
				var trsPos = {};
				var prevPos = false;
				
				$(window).mousemove(function(ev){
					if(dragging) {
						if( offsetTop + ev.clientY - offsetMouse > offsettHead) {
							if( offsetTop + ev.clientY - offsetMouse < tableHeight ){
								dragging.css('top', offsetTop + ev.clientY - offsetMouse );
								
								for(y in trsPos) {
									if(y >= offsetTop + ev.clientY - offsetMouse)
										break;
								}
								
								if( prevPos && prevPos != trsPos[y] ){
									prevPos.css('border-bottom', '1px solid #E6E6E6');
								}
								prevPos = trsPos[y];
								trsPos[y].css('border-bottom', '1px dotted #222');
								
							} else {
							dragging.css('top', tableHeight );
							}
						} else {
							dragging.css('top', offsettHead );
						}
					}
					return false;
				});
				
				$(window).mouseup(function(){
					if(dragging) {
						if(prevPos){
							prevPos.css('border-bottom', '1px solid #E6E6E6');
							if( dragging._row.get(0) != prevPos.get(0) ){
								if(prevPos.get(0).parentNode.nodeName.toLowerCase() =='thead')
									dragging._row.insertBefore($('tbody tr:first', $table));
								else {
									dragging._row.insertAfter(prevPos);
								}
								resetArrows($table);
							}
							prevPos = false;
						}
						dragging.remove();
						dragging = false;
					}
				});
				
				if(trs.length) {
					trs.each(function(){
						$('td:first', this).prepend('<div class="sort-controller"><span class="down"></span><span class="up"></span></div>');
						$('td:first .down', this).click(function(){
							var row = $(this).parents('tr:first');
							row.insertAfter(row.next());
							resetArrows($table);
							return false;
						});
						$('td:first .up', this).click(function(){
							var row = $(this).parents('tr:first');
							row.insertBefore(row.prev());
							resetArrows($table);
							return false;
						});
					}).mousedown(function(ev){
						
						
						var target = ev.originalTarget || ev.toElement || ev.srcElement;
						
						switch( target.nodeName.toLowerCase() ) {
							case 'a': case 'input':
								return true;
						}
						
						switch( target.className ) {
							case 'down': case 'up':
								return true;
						}
						
						
						if(jQuery.browser.msie && parseInt(jQuery.browser.version) < 7 ) {
							return true;
						}
						
						offsetMouse = ev.clientY;
						offsetTop = $(this).position().top;
						dragging = $('<table><tbody></tbody></table>').append( $(this).clone() ).appendTo(wrapper).css({
							'width': $table.css('width') - 2,
							'background': '#FFF',
							'margin': 0,
							'position': 'absolute',
							'top': $(this).position().top,
							'left': 1,
							'opacity': 0.75,
							'border': '1px solid #AAA'
						}).attr('class', $table.attr('class'));
						dragging._row = $(this);
						
						trsPos = {};
						var f = true;
						$('tr', $table).each(function(){
							if(!f)
								trsPos[$(this).position().top] = $(this);
							else{
								trsPos[$(this).position().top + 20] = $(this);
								f = false;
								}
						});
						
						var tds = $('td', this);
						var i = 0;
						$('td', dragging).each(function(){
							$(this).css('width', $(tds.get(i++)).css('width') );
						});
						
						return false;
					});
				}
					
				resetArrows(this);
			});
		
		})();
		
		
		$('#content-search-plot .next').click(function(){
			var nw = window.open('/layout/templates/javascript/print-plot.html', 'print-plot', 'height=600px,width=980px, scrollbars, resizable');
			
			return false;
		});
		
	});
	
	
	
})(jQuery);







/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 *
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            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
        }
        // CAUTION: 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;
    }
};

