jQuery.fn.replaceWith = function(newhtml) {

	$(this).before('<div class="replaceholder" style="visibility:hidden"></div>');
	$(this).remove();
	$('div.replaceholder').after(newhtml);
	$('div.replaceholder').remove();
	return this;
};

jQuery.fn.wrapInner = function(newhtml) {

	ftend = newhtml.indexOf('>');	
	firsttag = newhtml.substring(0,ftend+1);
	lasttag = newhtml.substring(ftend+1,newhtml.length);
	//console.log(firsttag);
	//console.log(lasttag);
	$(this).prepend(firsttag);
	$(this).append(lasttag);
	return this;

};


var sel_cat = null;
var sel_country = null;
var last_mc = null;
var last_country = null;
var last_countryv = null;
var last_sc = null;
var last_mcv = null;
var last_scv = null;
var btn_cnt = 0;
var globaltrig = null;
var frms = [['/listings/actions/add_to_favourites','favourite',"$('div#content').prepend(data)",'','Added to favourites'],['/listings/actions/send','sendtofriend',"$('div#portfolio-item').after(data)",'','Sent to friend'],['/listings/actions/add_to_favourites','favourite','createTr(data,trigger)','deleteTr(trigger)','Added to favourites'],['/listings/actions/report','frm-report',"$('div#footer').append(data)",'','Listing reported']];
var logged = null;
var delcnt = 0;
var about = null;
var country = ['','country_1','','country_3','','','country_6'];


$(document).ready(function(){

	/* select categories for forms with category selectors */
	sel_cat1 = $($('select#main-category'));
	sel_cat2 = $($('select#search-type'));
	if (sel_cat1.size() > 0) {
		activateSelCat();
	}	
	if (sel_cat2.size() > 0) {
		activateSelCatSearch();
	}	
	
	/* button replacement */
	$('.button:submit').each(function(){
		replaceButton(this);
	}); 
	
	
	/* website input field */
	$('input#website').each(function(){
		if($(this).val() == '') {
			$(this).val('http://');
		}
	});
	
	
	/* country selectors for registration etc */
	sel_country = $($('#content').find('select#country'));
	if(sel_country.size() > 0) {
		// ok we are on a page where there is menue like that

		activateSelCountry();
		
	}
	
	/* before hijaxing check if user is logged in */
	$('div#your-favourites').size() > 0 ? logged=true : logged=false;
	
	if (logged) {
	
		/* add to favourites via ajax */
		$('a#add-favourites').click(function(me){
			me.preventDefault();
			dynamicForm(0,$(this));
			return false;
		});
		$('a.expand-text').not('#send-friend').not('#show-contact-form').click(function(me){
			me.preventDefault();
			dynamicForm(2,$(this));
			return false;
		});
	
	}
	
	/* delete favouite */
	delcnt = $('a.favdel').size();
	$('a.favdel').click(function(me){
		me.preventDefault();
		var trigger = $(this);
		delFavourite(trigger);
		return false;
	});
	
	
	/* send to friend via ajax */
	$('a#send-friend').click(function(me){
		me.preventDefault();
		dynamicForm(1,this);
		return false;
	});
		
	
	
	
	/* report via ajax */
	$('p#report-problem a').click(function(me){
		me.preventDefault();
		//console.log('click');
		dynamicForm(3,this);
		return false;
	});
	
	

	
	
	
	
	
	$('a#show-contact-form').size() > 0 ? about=true : about= false;
	
	if (about) {
	/* show if it has errors */
		if ($('form#frm-advertiser-contact p.error').html().indexOf('Please') != -1) {
			$('form#frm-advertiser-contact').slideDown();
			$('a#show-contact-form').addClass('active');
		}
	/* about page contact form */
		$('a#show-contact-form').click(function(me) {
			me.preventDefault();
			var frm = $(this).parent().next();
			//console.log($(this).is('.active'));
			if ($(this).is('.active')) {
				$(this).removeClass('active');
				frm.slideUp();
			} else {
				$(this).addClass('active');
				frm.slideDown();
			}
			return false;
		});
		$('form#frm-advertiser-contact a#hide-contact-form').click(function(me){
			me.preventDefault();
			$('a#show-contact-form').trigger('click');
			return false;
		});
		
		$('form#frm-advertiser-contact').submit(function(me){
			me.preventDefault();
			url = '.php?url='+$(this).attr('action');
			n = $(this).find('input#your-name').val();
			m = $(this).find('input#message').val();
			e = $(this).find('input#your-email').val()
			tm = $(this).find('input#your-message').val();
			s = $(this).find('input#Send').val();
			frm = $(this);
			$.post('/dynamic'+url,{'your_name':n,'your_email':e,'your_message':tm,message:m,Send:s},function(data){
				//console.log(data);
				if (data.indexOf("check") > -1) {
					frm.find('p.error').html('There was an error sending your mail. Please check that you have filled in all fields');
				} else {
					frm.before('<p id="contact_alert" class="scheme" style="float:none;clear:both;padding:10px;margin-top:10px;">Your enquiry has been sent.</p>');
					frm.slideUp();
					$('a#show-contact-form').removeClass('active');
					setTimeout('removeAlert()',1000);
				}
				// else 
				// error 
			});
			return false;
			
		});
		
	}

	
	
	/* favourites and results opening opening */

	$('tr.details').find('a.expand').click(function(me){
		me.preventDefault();
		var row = $($(this).parent().parent());
	
		if (row.is('.active')) {
			row.next().find('table').slideUp(function(){
				//row.next().remove();
				row.removeClass('active');
				if (row.next().next().is('.active')) {
					row.addClass('active-prev');
				}
				if (row.prev().prev().is('.active')) {
					row.addClass('active-next');
				}
				row.next().next(".details").removeClass('active-next');
				row.prev().prev(".details").removeClass('active-prev');
			});

		} else {
			row.addClass('active');
			row.removeClass('active-next');
			row.removeClass('active-prev');
			//console.log(row.next().next());
			row.next().next(".details").not('.active').addClass('active-next');
			row.prev().prev(".details").not('.active').addClass('active-prev');
			row.next().find('table').slideDown();
			
			/* activate image navigation */
			row.next().find('td.photos a').not('.nav-next').each(function(){
				if (row.next().find('td.photos div.imgs').size() < 1) {
					/* get images but only when we haven't already done so */
					var url = $(this).attr('href');
					//console.log(url);
					var el = $(this);
					url = url.replace('/view/image/','/');
					$.get('/dynamic'+url,function(data){
	
						$(el).replaceWith(data);
						imgNav(row);
					});
				}
				
				
			
			});	
		}
		return false;
	});
	
	/* image results opening */
	$('table#search-results').find('div.imagerelated').find('a.arrow').click(function(me){
		me.preventDefault();
		
		// activate image navigation
		// if we haven't already done so... we can tell by the image navigation....
		if ($(this).parent().parent().find('div.imgs').find('a').size()<2) {
			var url = $(this).attr('href');
			var tel = $(this).parent().parent();
			// get the image because this is the one we need to replace
			var el = $(tel).find('div.imgs').find('div');
			var exlstr = $(el).find('a').attr('href');
			url = url.replace('/view/image/','/');
			
			$.get('/dynamic'+url,function(data){
				data = data.replace('<div class="imgs" style="width:115px;height:115px;overflow:hidden;"><div style="width:1500px;">','');
				data = data.replace('</div></div>','');
				
				$(el).find('a').replaceWith(data);
			/// this is the imgNav function
				var td = $($(tel).find('div.imagerelated'));
				var tdp = $(td.find('p'));
				td.find('a.arrow').remove();
				var imgs = $($(tel).find('div.imgs'));
				var imgsd = $(imgs.find('div'));
				var no = imgs.find('img').size()-1;
				var curr = 0;
				
				// find which image is the current one
				var currcnt = 0;
				imgsd.find('a').each(function(){
					var tl = $(this).attr('href');
					if (tl.substring(tl.indexOf('/list')) == exlstr) {
						curr = currcnt;
						imgsd.animate({marginLeft: (curr*-115)},'slow');
					}
					currcnt++;
				});
				
				
				
				td.append('<a href="#" class="nav-prev">Previous</a><a href="#" class="nav-next">Next</a>');
				td.find('a.nav-next').click(function(me){
					me.preventDefault();
					if(curr < no) {
						curr++;
						//imgsd.css('margin-left',(curr*-115)+'px');
						imgsd.animate({marginLeft: (curr*-115)},'slow',function(){
							tdp.html(imgsd.find('a').eq(curr).find('img').attr('title'));
						});
					}
					return false;
				});
				td.find('a.nav-prev').click(function(me){
					me.preventDefault();
					if(curr > 0) {
						curr--;
						//imgsd.css('margin-left',(curr*-115)+'px');
						imgsd.animate({marginLeft: (curr*-115)},'slow',function(){
							tdp.html(imgsd.find('a').eq(curr).find('img').attr('title'));
						});
					}
					return false;
				});
				
				
				
			});
		}
	
	
		return false;
	});
	
	
	
});

function removeAlert() {
	$('p#contact_alert').remove();
}

function delFavourite(trigger) {


		$.get('/dynamic'+trigger.attr('href'),function(data){
			var url = window.location.href;
			var url_page = parseInt(url.substring(url.lastIndexOf('/')+1,url.length));
			var prev_url = url.substring(0,url.lastIndexOf('/')+1);
			url_page == 1? url_page = 1: url_page--;
			prev_url = prev_url+url_page;

			//var txt = $(data).find('p');
			trigger.html(data);
			setTimeout(function () {
				if (delcnt > 1) {
					delcnt--;
					var parent = $(trigger.parent().parent().parent().parent().parent().parent());
					parent.prev().remove();
					parent.prev().prev().removeClass('active-prev');
					parent.next().removeClass('active-next');
					parent.remove();
				} else {
					window.location.replace(prev_url);
				}
				
				},500);
			
		});

}


function imgNav(row) {
	var td = $(row.next().find('td.photos'));
	td.find('a.nav-next').remove();
	var imgs = $(row.next().find('td.photos div.imgs'));
	var imgsd = $(imgs.find('div'));
	var no = imgs.find('img').size()-1;
	var curr = 0;
	imgs.after('<a href="#" class="nav-prev">Previous</a><a href="#" class="nav-next">Next</a>');
	td.find('a.nav-next').click(function(me){
		me.preventDefault();
		if(curr < no) {
			curr++;
			//imgsd.css('margin-left',(curr*-115)+'px');
			imgsd.animate({marginLeft: (curr*-115)},'slow');
		}
		return false;
	});
	td.find('a.nav-prev').click(function(me){
		me.preventDefault();
		if(curr > 0) {
			curr--;
			//imgsd.css('margin-left',(curr*-115)+'px');
			imgsd.animate({marginLeft: (curr*-115)},'slow');
		}
		return false;
	});
}


function createTr(data,trigger) {
	var tr = $($(trigger).parent().parent());
	tr.after('<tr class="details active-next"><td colspan="3" style="padding:0;"></td></tr>');
	tr.next().find("td").html(data);
	tr.next().find('p.buttons').css('margin-left','9px');
}

function deleteTr(trigger) {
	//console.log('deletetr'+trigger);
	$(trigger).parent().parent().next().remove();
}

function deleteRp() {
	//console.log('deletetr'+trigger);
	$('p#report-problem').remove();
}

function dynamicForm(which,trigger) {
	//console.log('dynamic');
	var frm = $($("form[name='"+frms[which][1]+"']"));
	if (frm.size() < 1) {
		frm = $($('form#'+frms[which][1]));
	}
	if (trigger != null && $(trigger).is('.active')) {	
			frm.slideUp(function(){
			frm.remove();
			$(trigger).removeClass('active');
			eval(frms[which][3]);
		});	
	} else {
		if (frm.size() > 0) {
			frm.remove();
		}
		if (trigger != null) {
			$(trigger).addClass('loading');	
		}
		var cond = $(trigger).attr('href');
		//cond = cond.substring(cond.lastIndexOf('/'),cond.length);
		var condarr = cond.split('/');
		cond = '';
		for (var i in condarr) {
    		if(!(isNaN(parseInt(condarr[i])))) {
      		  cond += '/'+condarr[i];
   			}
		}
		$.get('/dynamic'+frms[which][0]+''+cond,function(data){
			processData(which,data,trigger);
		});	
	}
}

function doPost(action,vals,which,trigger,frm) {
	$.post(action,vals,function(data){
		//console.log(data.indexOf('<form');
		if (data == 'success' || data.indexOf('<form') == -1) {
			frm.slideUp(function(){
				//console.log(trigger);
				if (trigger != null) {
					$(trigger).removeClass('active');
					$(trigger).html(frms[which][4]);
					globaltrig = $($(trigger));
					setTimeout(function () {globaltrig.fadeOut(function(){$(this).remove();});},1500);
					if (which == 0 || which == 2) {
						var favpanel = $($('div#your-favourites'));
						var favinner = $($('div#favtemp'));
						if (favinner.size() < 1) {
							favpanel.wrapInner('<div id="favtemp"></div>');
							favinner = $($('div#favtemp'));
						}
						favinner.slideUp(function(){
							$.get('/dynamic/listings',function(data){
								//favinner.html(data);
								data = data.replace('<div id="your-favourites">','');
								//console.log(data);
								//data = data.substring(0,data.lastIndexOf('</div>'));
								//console.log(data);
								//favinner.html(data);
								favinner.slideDown();
							});
						});
						
					}
					
				}
			});
		} else {
			frm.slideUp(function() {
				frm.remove();
				processData(which,data,trigger);
			});
			
		}
	});

}

function processData(which,data,trigger) {
	eval(frms[which][2]);

	var frm = $($('div#content').find('form[name="'+frms[which][1]+'"]'));
	var frm = $($('div#content').find('form').filter(function() {
					if ($(this).attr('name') == frms[which][1]) {
						return true;
					} else {
						return false
					}
                }));
                
               
              //  ('form[name="'+frms[which][1]+'"]'));
	/* jquery bug attribute name not available straight away*/ 
	if (frm.size() < 1) {
		frm = $($('form#'+frms[which][1]));
	}
	//console.log(frm);
	frm.slideDown('slow',function(){
		if (trigger != null) {
			$(trigger).removeClass('loading');
			$(trigger).addClass('active');
		}
	});
	
	frm.find('.button:submit').each(function(){
		var btn = replaceButton(this);
		
		
		/// here we need to hijack the form
		btn = $(frm.find('a#btn-'+btn));
		btn.unbind();
		btn.click(function(me){
			me.preventDefault();
			var vals = [];
			frm.find('input:checkbox:checked').each(function(){
				vals.push({ name: $(this).attr('name'), value: $(this).val() });
			});
			frm.find('textarea').each(function(){
				vals.push({ name: $(this).attr('name'), value: $(this).val() });
			});
			frm.find('input:input').not(':checkbox').each(function(){
				vals.push({ name: $(this).attr('name'), value: $(this).val() });
			});
			if (which == 0 || which == 2) {
				vals.push({name: 'ajax', value: 'ajax'});
			}
			
			var action = frm.attr('action');
			action = '/dynamic'+action;
			doPost(action,vals,which,trigger,frm);
			
			
		
			return false;
		});
		
	});
	frm.find('a#hide-contact-form').click(function(me){
		me.preventDefault();
		frm.slideUp(function(){
			frm.remove();
			eval(frms[which][3]);
		});	
		if (trigger != null) {
			$(trigger).removeClass('active');
		}
		return false;
	});	
}


function replaceButton(which) {
	var txt = $(which).attr('value');
	var nm = $(which).attr('name');
	var id = $(which).attr('id');
	var frm = $(which).parents('form:first').attr('id');
	$(which).replaceWith('<input type="hidden" name="'+nm+'" id="'+id+'" value="'+txt+'" /><a class="arrow" href="#" id="btn-'+btn_cnt+'">'+txt+'</a>');
	var btno = btn_cnt;
	$('form#'+frm+' input').keypress(function(me){
		//console.log($(me+':focus'));
		if (me.keyCode == 13) {
			//console.log('key 13'); find option to figure out if the current field has focus
			//console.log(me.focus());
			//$('a#btn-'+btno).trigger('click');
			//$('form#'+frm).trigger('submit');
		}
	});
	$('a#btn-'+btn_cnt).click(function(me){
		me.preventDefault();
		$('form#'+frm).submit();
		return false;
	});
	btn_cnt++;
	return (btn_cnt-1);
}



/* select categories for forms with category selectors FUNCTIONS */
function activateSelCountry() {

	showSubCountry();
	sel_country.change(function(){
		showSubCountry();
	});
}

function activateSelCatSearch() {
	showSpecialisationsSearch();
	sel_cat2.change(function(){
		showSpecialisationsSearch();
	});
}
function activateSelCat() {
	showSpecialisations();
	sel_cat1.change(function(){
		showSpecialisations();
	});
}

function showSubCountry() {
	last_country = $($('#content').find('select#country option:selected'));
	if (last_countryv == null) {
		$('#content').find('div#w'+country[last_country.val()]).slideDown();
		last_countryv = last_country.val();
	}

	if (last_country.val() != last_countryv) {
		/* this menue has changed */
		if (country[last_countryv] != '') {
			$('#content').find('div#w'+country[last_countryv]).slideUp(function(){
				$('#content').find('div#w'+country[last_country.val()]).slideDown();
				last_countryv = last_country.val();		
			});
		} else {
			$('#content').find('div#w'+country[last_country.val()]).slideDown();
			last_countryv = last_country.val();		
		}
	} 
	
}


function showSpecialisations() {

	last_mc = $($('select#main-category option:selected'));
	if (last_mcv == null) {
		$('#col-2 div#specialisations-'+last_mc.val()).slideDown();
		last_mcv = last_mc.val();
	}

	if (last_mc.val() != last_mcv) {
		/* this menue has changed */
		$('#col-2 div#specialisations-'+last_mcv).slideUp(function(){
			$('#col-2 div#specialisations-'+last_mc.val()).slideDown();
			last_mcv = last_mc.val();		

			
		});

	} 
	
}

function showSpecialisationsSearch() {

	last_sc = $($('select#search-type option:selected'));
	if (last_scv == null && last_sc.val() != -1) {
		$('#col-1 div#specialisations-'+last_sc.val()).slideDown();
		last_scv = last_sc.val();
	}
	if (last_sc.val() != last_scv) {
		if (last_scv != -1) {
			$('#col-1 div#specialisations-'+last_scv).slideUp(function(){
				$('#col-1 div#specialisations-'+last_sc.val()).slideDown();
				last_scv = last_sc.val();				
			});
		} else {
			$('#col-1 div#specialisations-'+last_sc.val()).slideDown();
			last_scv = last_sc.val();						
		}

	}

	
}