// JavaScript Document

var PreSimpleSwapOnload =(window.onload)? window.onload : function(){};
window.onload = function(){PreSimpleSwapOnload(); SimpleSwapSetup();}

function SimpleSwap(el,which){
        el.src=el.getAttribute(which||"origsrc");
}

function SimpleSwapSetup(){
  var x = document.getElementsByTagName("img");
  for (var i=0;i<x.length;i++){
    var oversrc = x[i].getAttribute("oversrc");
    if (!oversrc) continue;
    // preload image
    // comment the next two lines to disable image pre-loading
    x[i].oversrc_img = new Image();
    x[i].oversrc_img.src=oversrc;
    // set event handlers
    x[i].onmouseover = new Function("SimpleSwap(this,'oversrc');");
    x[i].onmouseout = new Function("SimpleSwap(this);");
    // save original src
    x[i].setAttribute("origsrc",x[i].src);
  }
}

function redirectNEWimg(childID,parentID,whatID,typeID)
{
this.location = "include/actionAttach.php?do=add&what="+whatID+"&child="+childID+"&parent="+parentID+"&type="+typeID;
}

function setCalendar(elID) {
	var curDay = $('#get'+elID+' .day').val();
	var daysInMonthArray= new Array(-1,31,($('#get'+elID+' .year').val() % 4 ? 28:29),31,30,31,30,31,31,30,31,30,31);
	var day=month=new Array();
	for (var i=1;i<=31;i++)
		day[i-1] = i > 9 ? i : "0"+i.toString();
	for (var i=1;i<=12;i++)
		month[i-1] = i > 9 ? i : "0"+i.toString();
	//check selected month, if ! > 0 allow current set date
	if ($('#get'+elID+' .month').val() > 0) {
		$('#get'+elID+' .day').html("<option value=\"-1\">Day:</option>");
		if (curDay > daysInMonthArray[$('#get'+elID+' .month').val()]) {
			for (i=1;i <= daysInMonthArray[$('#get'+elID+' .month').val()];i++) $('#get'+elID+' .day').append("<option value=\""+i+"\">"+i+"</option>");
			$('#get'+elID+' .day').val(daysInMonthArray[$('#get'+elID+' .month').val()]);
		} else {
			for (i=1;i <= daysInMonthArray[$('#get'+elID+' .month').val()];i++) $('#get'+elID+' .day').append("<option value=\""+i+"\">"+i+"</option>");
			$('#get'+elID+' .day').val(curDay);
		}
	}
	//set date if all values are set ok
	if ($('#get'+elID+' .day').val() > 0 && $('#get'+elID+' .month').val() > 0 && $('#get'+elID+' .year').val() > 0)
		$('#reg'+elID).val($('#get'+elID+' .year').val()+"-"+month[$('#get'+elID+' .month').val()-1]+"-"+day[$('#get'+elID+' .day').val()-1]);
	else $('#reg'+elID).val();
}



// POP EDIT/CREATE BOX
function populate(elID, thisEl, itemID, dataType){
	$.ajax({
		url:URLPATH+'/includes/getItem.php', 
		data:'type='+dataType+'&itemID='+itemID, 
		success:function(response){
			$('#'+elID).html(response);
			openDialog(elID, thisEl);
		}
	});	
}
function newItem(elID, thisID, dataType){
	$.ajax({url:URLPATH+'/includes/newItem.php', 
		data:'type='+dataType, 
		success:function(response){
			$('#'+elID).html(response);
			openDialog(elID, thisID);
		}
	});	
}

function openDialog(elID, thisID, setWidth) {
	if (setWidth===undefined) setWidth = 450;
	$("#"+elID).dialog({
		bgiframe: true,
		autoOpen: false,
		modal: true,
		width:setWidth,
		minWidth:setWidth,
		maxWidth:setWidth,
		draggable:true,
		hide: 'clip',
		show: 'clip'
	});
	$('#'+elID).dialog('open');
	if (thisID !== undefined) $(thisID).each(function(){this.onclick=null;}).click(function(){$('#'+elID).dialog('open')});
}

var subCats = new Array(), curCat = 0;

function pickCategory(elcatID,elcatName) {
	$('#cat').val(elcatID);
	$('.choose-buttons').empty();
	$('#topcat-selected').append( $('<a/>').html(elcatName+" <small>(click me to start over)</small>").attr('href',URLPATH+'/advertise') );
	getListOfCats(elcatID);
	createAdvert();
	$("h2:contains('First, choose what you wish to sell:')").text('Now, select your categories:');
	if ($('p.hideme1').css('display') == 'none')
		$('p.hideme1').show();
		$('h2.hideme1').show();
		$('h2.showme1').hide();
		$('p.showme1').hide();
}

function addslashes(str) {
	return str.replace(/\\/g,'\\\\').replace(/\'/g,'\\\'').replace(/\"/g,'\\"').replace(/\0/g,'\\0').replace(/\//g,'\\/');
}

function getListOfCats(elcatID) {
	$('.choose-buttons').empty();
	$.ajax({
		url:URLPATH+'/includes/getcategory.php',
		data:{catID:elcatID},
		dataType:'json',
		success:function(json){
			if (json.category !== undefined) {
				if (json.category.length > 0) {
					var catSelect = $('.choose-buttons');
					var thisCatId,thisCatName;
					$.each(json.category,function() {
						catSelect.append( $('<a onclick=\"pickSubCategory('+this.catId+',\''+addslashes(this.catName)+'\');\" />').html(this.catName).addClass('category-item').append(' ') );
					});
				}
			}
		}
	});
}

function pickSubCategory(elcatID,elcatName){
	//var curCat = $().length;
	if ($('.subcat-selected:last').text() == '') $('.subcat-selected:last').append( $('<a/>').html('x').addClass('big-red').click( function(){ remSubCat( $(".subcat-selected").index(this.parentNode)  ); } ) );
	$('.subcat-selected:last').append( $('<a/>').html(' &bull; '+elcatName) );
	$('#subcat-chosen-box input:last').val(elcatID);
	getListOfCats(elcatID);
	if (!$('.next-subcat-button').is('button')){
		$('.choose-buttons').after( 
			$('<button/>').addClass('next-subcat-button').text('Click to Add Another Sub Category').click(function(){nextSubCat();}) 
		);
	}
	if ($('p.hideme2').css('display') == 'none')
		$('p.hideme2').show();
}

function removeImage(imgName) {
	$('input:contains(\''+imgName+'\')').remove();
}

function checkAdvertFields(){
	if ($('#aTitle').val().length > 0 && $('#aDesc').val().length > 0 && $('#submit-advert').length < 1)
		$('#create-advert').after($('<input type="submit" id="submit-advert" value="Submit Advert" />'));
	else if ($('#submit-advert').length > 0 && ($('#aTitle').val() == '' || $('#aDesc').val() == '')) $('#submit-advert').remove();
}

function nextSubCat(insertInput){
	if (insertInput === undefined) insertInput = true; 
	$('.subcat-selected:last').after( $('.subcat-selected:last').clone().empty() );
	if (insertInput)
		$('#subcat-chosen-box input:last').after($('<input type="hidden" name="subcat[]" />'));
	getListOfCats($('#cat').val());
	$('.next-subcat-button').remove();
}

function remSubCat (catIndex) {
	if (catIndex != -1) {
		if ( $('.subcat-selected').length > 1)
			$('.subcat-selected:eq('+catIndex+')').remove();
		else
			$('.subcat-selected:eq('+catIndex+')').empty();
		
		if ( $('#subcat-chosen-box input').length > 1) 
			$('#subcat-chosen-box input:eq('+catIndex+')').remove();
		else
			$('#subcat-chosen-box input:eq('+catIndex+')').val('');
		nextSubCat();
	}
}

function createAdvert() {
	//$('.next-subcat-button').remove();
	//$('#subcat-chosen-box').empty();
	$.ajax({
		url:URLPATH+'/includes/getAdvert.php',
		data:{catID:$('#cat').val()},
		success:function(response){
			$('#create-advert').html(response);
			sIFR.replace(eurostile, {
			  selector: '#midrifCont h1, #midrifCont h2, #midrifCont h3, #midrifCont h4',
			  wmode:'transparent',
			  css: [
			  		'.sIFR-root { color:#FFFFFF; }',
			  		'.account-type  { cursor:pointer; }',
			  		'#edit { color:#CCCCCC; }'
			  	]
			});
		}
	});
}
var t=null;
function checkCoupon() {
	clearTimeout(t);
	t=setTimeout(function () {
		$.ajax({
			url: URLPATH+'/includes/checkcoupon.php',
			data:{str:$('#couponcode').val()},
			success:function(res){
				$('#couponreturn').html($('<img src="'+URLPATH+'/images/'+(res == 0 ? 'cancel.gif':'tick.gif')+'" alt="" />') ).append(res == 0 ? '':res);
			}
		});
	},500); 
}



function changeCategory(selectID,changeID,elID,thisEl) {
	$('#obama').val(changeID);
	$('#catselect').val(selectID);
	openPromptDialog(elID,thisEl);
	return false;
}

function openPromptDialog(elID,thisEl, setWidth, setMaxHeight) {	
	if (setWidth===undefined) setWidth = 450;
	if (setMaxHeight===undefined) setMaxHeight=false;
	$("#"+elID).dialog({
		bgiframe: true,
		autoOpen: false,
		modal: true,
		width:setWidth,
		minWidth:setWidth,
		maxWidth:setWidth,
		maxHeight:setMaxHeight,
		draggable:true,
		hide: 'clip',
		show: 'clip',
		buttons:{
			'Ok':function() {
				$('#'+elID+'form').submit();
				$(this).dialog('close');
			},
			'Cancel':function() {
				$(this).dialog('close');
			}
		}
	});
	$('#'+elID).dialog('open');
	if (thisEl !== undefined) $(thisEl).each(function(){this.onclick=null;}).click(function(){$('#'+elID).dialog('open')});
	return false;
}



// show/hide menu option
function toggle(id) {
//	if ($('#'+id).css('display')=='none') 
	if ($('#'+id+':animated').size()==0) 
		$('#'+id).slideToggle();		
//	} else { 
//		$('#'+id).hide('blind');
//	}
}
function checkme(id) {
	if (document.getElementById(id).style.display!='none') { 
	$('#'+id).hide('blind');			
	}
}
//pop window
function openwindow(theURL,winName,features) { window.open(theURL,winName,features); }
var t=0;
function getCatMenu (thisEl,catID,innerVar) {
	clearTimeout(t);
	var dims=null,dims2 = null;
	var thisWidth=0,thisHeight=0;
	t = setTimeout(function() {
//		if (!$(thisEl).parent().children('ul').is('ul')) {
			if (innerVar === undefined || innerVar === false) { 
				dims = $(thisEl).parent().offset();
				thisWidth=$(thisEl).parent().width()+dims.left;
				thisHeight=dims.top;
			} else {
				dims = $(thisEl).parent().offset();
				dims2 = $(thisEl).parent().parent().offset();
				thisWidth=$(thisEl).parent().width();
				thisHeight=dims.top-dims2.top;
			}
			$(thisEl).parent().mouseleave(function(){$(this).children('ul').remove();});
			$(thisEl).after($('<ul style="position:absolute; left:'+thisWidth+'px; top:'+thisHeight+'px;"/>').mouseleave(function(){$(this).remove();}));
			$.ajax({
				url:URLPATH+'/includes/catMenu.php',
				data:{catid:catID,queryString:thisQueryString},
				success:function(resp){ $(thisEl).next('ul').html(resp); }
			});
//		}
	},200);
}

function getPerson(elID, thisID, dataType){

	$.ajax({url:URLPATH+'/include/getPerson.php', 
		data:'item='+dataType, 
		success:function(response){
			$('#'+elID).html(response);
			if (document.getElementById(elID).style.display=='none') { 
			$('#'+elID).show('blind', function(){});
			}
		}
	});	
}

// SORTABLE TABLE
//$(document).ready(function() {
//	FLIR.init({path:URLPATH+'/lib/'});
//	FLIR.replace(['h1','h2','h3','h4'],new FLIRStyle({mode:'wrap'}));
//	FLIR.replace(['div#menu li', 'div#menu li * li'],new FLIRStyle({mode:'wrap'}));
//	}) ;
