/**
 * FE JS Scripte - Models/index
 */

function downloadPdf() {
	$(document).ready(function() {
		var domain = window.location.hostname;
		$('input#sedcard_download').click(function(){
			var watchlist = $(this).attr('name');
			var fieldArr = new Array();
			var fieldArr = watchlist.split('_');
			var mid = fieldArr[2];
			var wl = fieldArr[3];
			var tmpScId = $('select#wl_model_select_'+mid).val().split('_');
			var scId = tmpScId[0];
			var type = tmpScId[1];
			if(scId > -1)
			{
				$('form#watchlist_model').attr('action','/models/downloadpdf/mid/'+mid+"/scId/"+scId+'/wl/'+wl+'/type/'+type);
				$('form#watchlist_model').submit();
				mid = null;
				type = null;
				return false;
			} else{
				alert("Keine Sedcard ausgewählt!");
			}
			return false;
		});
	});

}
downloadPdf();


function downloadSedcardFromModelDetails() {
    $(document).ready(function() {
        var baseUrl = 'http://' + window.location.hostname;
        $('#sedcard_select').change(function(){
            if ($(this).val() == -1) {
                return FALSE;
            }
            var location = baseUrl + $(this).val();
            //$(location).attr('href', location);
            window.location.replace(location);
        });
    });

}
downloadSedcardFromModelDetails();


function emailWatchList() {
	$(document).ready(function() {
		var domain = window.location.hostname;
		$('div#email > a[name="email-link"]').click(function(e){
			e.preventDefault();
			//now collect the names of the choosen sedcards and give an alert message,
			//when not for every model a sedcard is choosen
			var ok = true;
			$('div.selectmenu > select option:selected').each(function(){
				//get model id
				var modelId = $(this).parent().attr('id').split('_')[3];
				if ($('#item_wrapper_' + modelId).css('display') != 'none' && $(this).val() == -1) {
					ok = false;
					alert('Bitte wählen Sie für jedes Model eine Sedcard aus.');
					return false;//stop the each loop
				}
			});
			if (!ok) return false;//stop the function
			//if sedcards are choosen, set the form parameters
			$('form#watchlist_model').attr('action', $(this).attr('href'));
			//submit form
			$('form#watchlist_model').submit();
		});
	});
}
emailWatchList();

function deleteModel()
{
	$(document).ready(function() {
		var domain = window.location.hostname;
		$('input#wl_delete').click(function(){
			var watchlist = $(this).attr('name');
			var fieldArr = new Array();
			fieldArr = watchlist.split('_');
			var id = fieldArr[2];
			var wl = fieldArr[3];
			a = document.cookie;
			session = a.substring(0,a.indexOf('='));
			if (a.indexOf(';') != -1) {
				session = a.substring(a.indexOf('=')+1,a.indexOf(';'));
			} else {
				session = a.substr(a.indexOf('=')+1,a.length);
			}
			if (id!= 0) {
                var watchlistSession = $.cookie('watchlist_session');
				$.ajax({
		            type: 'POST',
		            dataType: 'json',
		            url: 'http://'+domain+'/models/deletewatchlistmodel',
		            async: false,
					data: {
                        id: id,
                        session: watchlistSession // jquery.cookie.js (at begin of this page)
                    },
		            success: function(data){
		            	$('#item_wrapper_'+data.model_id).remove();
                        //set session new to prolong it
                        resetCookie(watchlistSession, data.watchlist_id);
		            	return false;
			        }
				});


				mid = null;
				return false;
			}else{
				alert("Keine Sedcard ausgewählt!");
			}
			return false;
		});
	});

}
deleteModel();


function emptySearchUserInput()
{
	$(document).ready(function() {
		$("input#searchfield").click(function(){
			$('input#searchfield').val('');
		});
	});

}
emptySearchUserInput();


function flagWatchlistItems()
{
	$(document).ready(function() {
		$('div.watchlist').each(function(el){
			var  label = $(this).attr('label');
			if(label !== ''){
				$(this).attr('class',"watchlist activ");
			}
		});
	});

}
flagWatchlistItems();


/* Suche  auf der ModelSeite Auswahl Attrute */
function searchModels(){
	var domain = window.location.hostname;
	$(document).ready(function() {
		$('#functions').change(function(){
			var sex 	= $('#sex').val();
			var age 	= $('#age').val();
			var hair 	= $('#hair_color').val();
			var eyes 	= $('#eyes').val();
			var tags 	= $('#tags').val();
			var page    = $('#page').val()
			$('#modelsearch').submit();
		});
	});

}
searchModels();


function collectWatchlistIds(){
	$(document).ready(function() {
		$('#input').change(function(){
			var sex 	= $('#sex').val();
			var age 	= $('#age').val();
			var hair 	= $('#hair_color').val();
			var eyes 	= $('#eyes').val();
			var tags 	= $('#tags').val();
			var page    = $('#page').val();
			var submit  = $('#submit').val();
			var domain = window.location.hostname;
			$('#modelsearch').submit();
		});
	});
}
collectWatchlistIds();


function submitSearchNav(){
	$(document).ready(function(){
		$('#search_nav').click(function(){
			var age = $('#age').val();
			var domain = window.location.hostname;
			$('#searchnavform').submit
		});
	});
}
submitSearchNav()


function submitMetaSearch(){
	$(document).ready(function() {
		$('input#searchfield').keypress(function(e) {
			  if (e.keyCode == '13') {
			     e.preventDefault();
			     $('#metasearch').submit()
			   }
		});
	});
}
submitMetaSearch();


function submitMetaSearchByImage(){
	$(document).ready(function() {
		$('input#search-submit').click(function() {
			e.preventDefault();
			$('#metasearch').submit();
		});
	});
}
submitMetaSearchByImage();


function watchlistHint()
{
	$(document).ready(function() {
		$("a[name='nolist']").click(function(event) {
			alert("Sie haben noch kein Model für die Merkliste ausgesucht!");
			return false;
		});
	});

}
watchlistHint();


function watchlistDetails()
{
	$(document).ready(function() {
		$("div.watchlist").click(function() {
			var domain = window.location.hostname;
			var watchlist = $(this).attr('id');
			var fieldArr = new Array();
		    fieldArr = watchlist.split('_');
		    var id = fieldArr[1];

			a = document.cookie;
			session = a.substring(0,a.indexOf('='));
			if (a.indexOf(';') != -1) {
				session = a.substring(a.indexOf('=')+1,a.indexOf(';'));
			} else {
				session = a.substr(a.indexOf('=')+1,a.length);
			}

            //prepare person type part
            var typePart = null;
            if ($('a.watchlist-link').attr('href').match(/kids/i)) {
                typePart = '/kids/1';
            } else {
                typePart = '/adults/1';
            }

            var watchlistSession = $.cookie('watchlist_session');
            //var watchlistSession = readCookie('watchlist_session');
			if ($(this).hasClass('activ')) {
				$.ajax({
		            type: 'POST',
		            dataType: 'json',
		            url: 'http://'+domain+'/models/deletewatchlistmodel',
		            async: false,
					data: {
                        id:id,
                        session: watchlistSession // jquery.cookie.js (at begin of this page)
                    },
		            success: function(result){
		            	if(result.watchlist_id == 0) {
                            var url = '/models/index' + typePart;
		            		$('#watchlist').html('<a class="watchlist-link" name="nolist" href="' + url + '" >Merkliste</a>');
		            		watchlistHint();
                            //set session new to prolong it
                            resetCookie(watchlistSession, result.watchlist_id);
		            	}
		            	return false;
			        }
				});
			} else {
				$.ajax({
		            type: 'POST',
		            dataType: 'json',
		            url: 'http://'+domain+'/models/savewatchlist',
		            async: false,
					data: {
                        id:id,
                        session: watchlistSession // jquery.cookie.js (at begin of this page)
					},
		            success: function(result){
		                var url = '/models/watchlist/wl/' + result.watchlist_id + typePart;
		            	$('#watchlist').html('<a class="watchlist-link" href="' + url + '" title="Hier können Sie die Models auf Ihrer Merkliste (gelber Stern unten rechts im Model-Fenster) anschauen">Merkliste</a>');
                        //set session new to prolong it
                        resetCookie(watchlistSession, result.watchlist_id);
		            	return false;
			        }
				});
			}
			$(this).toggleClass('activ');
			return false;
		});
	});

}
watchlistDetails();

function resetCookie(watchlistSession, watchlistId)
{
    //first delete cookie
    $.cookie('watchlist_session', null, {path: '/'});
    //eraseCookie('watchlist_session');
    if (watchlistId != 0) {
        //set it new with expire time 30 days from now onwards
        $.cookie('watchlist_session', watchlistSession, { expires: 30, path: '/' });
        //createCookie('watchlist_session', watchlistSession, 30, '/');
    }

}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function createCookie(name,value,days,path) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path="+path;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

